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

时间:2014-12-18 12:31:42

标签: 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_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")

用户已成功创建。当我从管理员端看到用户被创建时。但是当我登录时,用户名和密码都没有匹配。

但是当我从管理员和登录创建一个用户时,它没有任何错误登录..我不知道什么是错的。我正在使用自定义用户模型。

在管理员方面,我将用户is_active和is_general_user设为true。我想如果从admin创建的用户可以登录,那么从视图创建的用户也应该登录。

这里有什么不对?我在哪里弄错了?

1 个答案:

答案 0 :(得分:2)

您已正确覆盖表单的保存方法,以通过user.set_password()设置哈希密码。但是你永远不会从你的视图中调用save:相反,你直接在视图的form_valid方法中实例化一个GeneralUser,然后直接从cleaning_data设置密码,因此它不会被哈希。

从视图中删除该实例化,然后调用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