Python 成功创建用户后django用户登录失败

Python 成功创建用户后django用户登录失败,python,django,view,login,Python,Django,View,Login,我有以下表格: class GeneralUserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'duplicate_username': ("This Username already exists."), 'password_mismat

我有以下表格:

class GeneralUserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
    'duplicate_username': ("This Username already exists."),
    'password_mismatch': ("The two password fields didn't match."),
}
username = forms.RegexField(label=("Username"), max_length=30,
    regex=r'^[\w.+-]+$',
    help_text=("Required. 30 characters or fewer. Letters, digits and "
                "/./+/-/_ only."),
    error_messages={
        'invalid': ("This value may contain only letters, numbers and "
                     "./+/-/_ characters.")}, widget=forms.TextInput(attrs={'class':'input username'}))
password1 = forms.CharField(label="Password",
    widget=forms.PasswordInput(attrs={'class':'input username'}))
password2 = forms.CharField(label=("Password confirmation"),
    widget=forms.PasswordInput(attrs={'class':'input username'}),
    help_text=("Enter the same password as above, for verification."))
email = forms.EmailField(label="Email", widget=forms.TextInput(attrs={'class':'input username'}))
#gender = forms.CharField(widget=forms.PasswordInput(attrs={'class':'input username'}))
date_of_birth = forms.CharField(label=("Date of birth"),
    widget=forms.TextInput(attrs={'class':'input username', "placeholder": "YYYY-MM-DD"}))

def __init__(self, *args, **kwargs):
    super(GeneralUserCreationForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
    self.fields['gender'].widget.attrs['style'] = 'width:190px; height:40px; font-family:arial; border:1px solid #CCC;'
class Meta:
    model = GeneralUser
    fields = ("username", "email", "gender", "date_of_birth")
def clean_username(self):
    # Since User.username is unique, this check is redundant,
    # but it sets a nicer error message than the ORM. See #13147.
    username = self.cleaned_data["username"]
    try:
        User._default_manager.get(username=username)
    except User.DoesNotExist:
        return username
    raise forms.ValidationError(
        self.error_messages['duplicate_username'],
        code='duplicate_username',
    )
def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'],
            code='password_mismatch',
        )
    return password2
def save(self, commit=True):
    user = super(GeneralUserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user
我有创建用户的视图:

class GeneralUserCreateView(CreateView):

form_class = GeneralUserCreationForm
template_name = "general_user.html"

def form_valid(self, form, *args, **kwargs):
    user = GeneralUser()
    user.username = form.clean_username()
    user.email = form.cleaned_data['email']
    user.password = form.cleaned_data['password1']
    user.gender = form.cleaned_data['gender']
    user.date_of_birth = form.cleaned_data['date_of_birth']
    user.is_active = True
    user.is_general_user = True
    user.save()
    title = "Welcome to something"
    content = "Thank you for using our system."
    send_mail(title, content, settings.EMAIL_HOST_USER, [user.email], fail_silently=True)

    return redirect("home_question")
用户已成功创建。当我从管理端看到用户被创建。但当我登录时,它说用户名和密码不匹配

但是,当我从管理员创建一个用户并登录时,它会在没有任何错误的情况下登录。。我不知道怎么了。我使用的是自定义用户模型

在管理端,我将用户设置为活动用户和一般用户。我认为如果从admin创建的用户可以登录,那么从view创建的用户也应该登录


这里怎么了??我在哪里出错了???

您已经正确地重写了表单的save方法,通过
user.set\u password()
设置哈希密码。但您从不从视图中调用save:相反,您直接在视图的
form\u valid
方法中实例化GeneralUser,然后直接从清除的\u数据设置密码,因此它不会散列

从视图中删除该实例化,并调用super方法(它调用
form.save()
):


为什么不在表单保存方法中执行此操作?
def form_valid(self, form, *args, **kwargs):
    response = super(GeneralUserCreateView, self).form_valid(form, *args, **kwargs)
    user = self.object
    title = "Welcome to something"
    content = "Thank you for using our system."
    send_mail(title, content, settings.EMAIL_HOST_USER, [user.email], fail_silently=True)
    return response