【发布时间】:2021-06-06 11:37:54
【问题描述】:
我在做什么
我在 forms.py 中使用 ModelForm 并在 views.py 中使用 FormView 来制作注册表单。我让用户在登录时使用他们的电子邮件作为他们的用户名,以便他们在丢失时可以轻松设置新密码。
错误图片
它只是在我的控制台中抛出了IntegrityError。
IntegrityError at / NOT NULL contraint failed
我试图解决的问题
- 我删除了所有的迁移文件和 db 文件,这样我的数据库中就不会有任何重复的用户。然后我创建了新的超级用户,然后创建了新用户。
- 我在
Meta类中删除了fields中的email字段,然后创建了电子邮件的清理方法(def clean_email(self):)。但是,此解决方案显然不起作用,因为它会删除我的注册表单中的电子邮件字段。
源代码
以下是我所有可能与该主题相关的源代码。
- 模板/用户/signup.html
{% block content %}
<section id="signup">
<form method="POST", action="{% url 'users:signup' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Signup</button>
</form>
</section>
{% endblock content %}
- users/forms.py
class SignupForm(forms.ModelForm):
class Meta:
model = models.User
fields = ['first_name', 'last_name', 'email']
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput, label='Confirm Password')
# Validating password
def clean_confirm_password(self):
password = self.cleaned_data.get('password')
confirm_password = self.cleaned_data.get('confirm_password')
if password != confirm_password:
raise forms.ValidationError('Password should be matched!')
else:
return password
def save(self, *args, **kwargs):
user = super().save(commit=False)
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user.username = username
user.set_password = password
user.save()
- users/view.py
class SingupView(FormView):
template_name = 'users/signup.html'
form_class = forms.SignupForm
success_url = reverse_lazy('common:home')
def form_valid(self, form):
form.save()
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
user = authenticate(self.request, username=email, password=password)
if user is not None:
login(self.request, user)
return super().form_valid(form)
我的 github 仓库是https://github.com/donghhan/knowner-website.git
请帮帮我!
【问题讨论】:
标签: python django django-views django-forms