77 lines
3.1 KiB
Python
77 lines
3.1 KiB
Python
from django import forms
|
|
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
|
|
from django.db import transaction
|
|
|
|
from control.models import Plan, PlanApplication
|
|
|
|
from .models import User
|
|
|
|
|
|
class TopLCAuthenticationForm(AuthenticationForm):
|
|
username = forms.CharField(label="用户名", widget=forms.TextInput(attrs={"autofocus": True}))
|
|
password = forms.CharField(label="密码", strip=False, widget=forms.PasswordInput())
|
|
|
|
error_messages = {
|
|
"invalid_login": "用户名或密码不正确。",
|
|
"inactive": "该账号已被停用。",
|
|
}
|
|
|
|
|
|
class RegistrationForm(UserCreationForm):
|
|
display_name = forms.CharField(label="姓名", max_length=100)
|
|
email = forms.EmailField(label="邮箱")
|
|
phone = forms.CharField(label="手机", max_length=32, required=False)
|
|
company_name = forms.CharField(label="公司", max_length=160, required=False)
|
|
plan = forms.ModelChoiceField(
|
|
label="申请套餐", queryset=Plan.objects.none(),
|
|
help_text="注册时一并申请;内部员工核实身份后免费。标注“暂未开放付款”的套餐仅登记申请,不扣款、不立即开通付费服务。",
|
|
)
|
|
accept_terms = forms.BooleanField(label="我同意遵守公司网络服务使用规则")
|
|
|
|
class Meta(UserCreationForm.Meta):
|
|
model = User
|
|
fields = (
|
|
"username",
|
|
"display_name",
|
|
"email",
|
|
"phone",
|
|
"company_name",
|
|
"password1",
|
|
"password2",
|
|
)
|
|
labels = {"username": "用户名"}
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
plans = Plan.objects.filter(
|
|
active=True, employee_benefit=False,
|
|
audience__in=[Plan.Audience.EXTERNAL, Plan.Audience.ALL],
|
|
).order_by("sort_order", "price_cny", "pk")
|
|
self.fields["plan"].queryset = plans
|
|
self.fields["plan"].label_from_instance = lambda plan: plan.application_label()
|
|
default = plans.first()
|
|
if default is not None:
|
|
self.fields["plan"].initial = default.pk
|
|
else:
|
|
self.fields["plan"].help_text = "暂未配置可申请套餐,请联系管理员;不会创建没有套餐申请的账号。"
|
|
|
|
def clean_email(self):
|
|
email = self.cleaned_data["email"].strip().lower()
|
|
if User.objects.filter(email__iexact=email).exists():
|
|
raise forms.ValidationError("该邮箱已经注册。")
|
|
return email
|
|
|
|
def save(self, commit=True):
|
|
user = super().save(commit=False)
|
|
user.email = self.cleaned_data["email"]
|
|
user.display_name = self.cleaned_data["display_name"]
|
|
user.phone = self.cleaned_data.get("phone", "")
|
|
user.company_name = self.cleaned_data.get("company_name", "")
|
|
user.identity_type = User.IdentityType.EXTERNAL
|
|
user.account_status = User.AccountStatus.PENDING
|
|
if commit:
|
|
with transaction.atomic():
|
|
user.save()
|
|
PlanApplication.submit(user=user, plan=self.cleaned_data["plan"], note="注册时提交的套餐申请")
|
|
return user
|