我设法获得了一个额外的字段-“登录”页面上的state_name
(使用forms.ModelForm
),但是我正在努力将其保存在数据库中。
我有2个数据库连接,默认数据库用于保留Django表,而project_db用于保留程序表,这是否引起了问题?或带有forms.py文件?
下面是forms.py文件。
class UsersRegisterForm(forms.ModelForm):
class Meta:
model = User
fields = [
"username",
"state_name",
"email",
"confirm_email",
"password",
]
username = forms.CharField()
state_name = forms.ModelChoiceField(queryset=SchPartneredStates.objects.all(),empty_label=None)
email = forms.EmailField(label="Email")
confirm_email = forms.EmailField(label="Confirm Email")
password = forms.CharField(widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(UsersRegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs.update({
'class': 'form-control',
"name": "username"})
self.fields['state_name'].widget.attrs.update({
'class': 'form-control',
"name": "state_name"})
self.fields['email'].widget.attrs.update({
'class': 'form-control',
"name": "email"})
self.fields['confirm_email'].widget.attrs.update({
'class': 'form-control',
"name": "confirm_email"})
self.fields['password'].widget.attrs.update({
'class': 'form-control',
"name": "password"})
def clean(self, *args, **keyargs):
email = self.cleaned_data.get("email")
confirm_email = self.cleaned_data.get("confirm_email")
username = self.cleaned_data.get("username")
state_name = self.cleaned_data.get("state_name")
password = self.cleaned_data.get("password")
if email != confirm_email:
raise forms.ValidationError("Email must match")
email_qs = User.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError("Email is already registered")
username_qs = User.objects.filter(username=username)
if username_qs.exists():
raise forms.ValidationError("User with this username already registered")
if len(password) < 8: # you can add more validations for password
raise forms.ValidationError("Password must be greater than 8 characters")
return super(UsersRegisterForm, self).clean(*args, **keyargs)