Django用户创建

时间:2017-09-04 23:50:17

标签: python django

我正在使用Django中的内置UserCreationForm进行基本用户创建。

这是我的views.py:

def user_register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            raw_password = form.cleaned_data['password1']
            user = User.objects.create_user(username=username)
            if raw_password:
              user.set_password(raw_password)
            else:
              user.set_unusable_password()
            user.save()
            return redirect('home')
    else:
        form = UserCreationForm()
        return render(request, 'registration/register.html', {'form':  form})

但是,在注册用户并被重定向到主页后,我的管理页面中看到的用户数量没有变化;没有创建用户。 知道我在这里做错了什么吗?

4 个答案:

答案 0 :(得分:0)

不知道为什么你可以在没有使用创建的情况下重定向到家,但你应该处理的情况表格不是vaild并从form.is_valid()块中删除form.save():

form = UserCreationForm(request.POST)
if form.is_valid():
    # remove form.save()
    ....
else:
    print(form.errors.as_text())
    return render(request, 'registration/register.html', {'form':  form})

或覆盖UserCreationForm的保存方法,就像我这样做:

def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

完整的演示是:

from django.views.generic import *
class RegisterView(FormView):
    template_name = 'registration/register.html'
    form_class = UserCreationForm
    success_url = reverse_lazy('home')

    def form_valid(self, form):
        form.save()
        return HttpResponseRedirect(self.get_success_url())

forms.py

class UserCreationForm(forms.ModelForm):
    error_messages = {
        'duplicate_username': u"duplicate username",
        'password_mismatch': u"password_mismatch",
        'duplicate_email': u'duplicate email'
    }

    username = forms.RegexField(
        max_length=30,
        regex=r'^[\w.@+-]+$',
        error_messages={
            'invalid': u"onlay can contaions symbol @/./+/-/_",
            'required': u"required"
        },
        label='username'
    )
    email = forms.EmailField(
        error_messages={
            'invalid': u"email invalid",
            'required': u'required'},
        label='email'
    )
    password1 = forms.CharField(
        widget=forms.PasswordInput,
        error_messages={
            'required': u"required"
        },
        label='password1 '
    )
    password2 = forms.CharField(
        widget=forms.PasswordInput,
        error_messages={
            'required': u"required"
        },
        label='password2'
    )

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update({'class': 'form-control'})
        self.fields['email'].widget.attrs.update({'class': 'form-control'})
        self.fields['password1'].widget.attrs.update({'class': 'form-control'})
        self.fields['password2'].widget.attrs.update({'class': 'form-control'})

    class Meta:
        model = User
        fields = ("username", "email")

    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.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages["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"]
            )
        password_validation.validate_password(password2)
        return password2

    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(
            self.error_messages["duplicate_email"]
        )

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

答案 1 :(得分:0)

尝试:

from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.contrib.auth.models import User

def user_register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user=User.objects.create_user(username=username, password=password)
            user.save()
            #Below 2 lines, if you want user to get logged in
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'registration/register.html', {'form':  form})

答案 2 :(得分:0)

我不知道为什么要多次保存这个物体。记录here时,在 UserCreationForm 实例中调用 form.save()时,Django将创建用户,设置密码(来自 > password1 字段),将实例保存在数据库中并为您返回用户。所以 User.objects.create_user user.save()只会再次保存对象。

很可能它不是你问题的解决方案,但你尝试过这样:

def user_register(request):
   form = UserCreationForm() 
   if request.method == 'POST':
       form = UserCreationForm(request.POST)
       if form.is_valid():
          user = form.save()
          # if you want to authenticate your user or log any info, do it here
          return redirect('home')
   # I wouldn't use the else statement here, so if there are errors in the form you probably want the same template to be rendered, in order to show the form errors to your user.
   return render(request, 'registration/register.html', {'form':  form})

答案 3 :(得分:0)

感谢所有帮助我思考的人。当然,似乎答案比我想象的要简单得多。我的新user_register视图是:

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect

def user_register(request):
   form = UserCreationForm(request.POST)
   if form.is_valid():
       form.save()
       return redirect('home')
   else:
       return render(request, 'registration/register.html', {'form':   form})