我如何在django model User中注册用户

时间:2017-07-26 19:10:17

标签: python django django-models django-forms django-views

我已尽力在模型用户中存储价值,但我不能指导我错误是什么以及为什么它不起作用。 相关代码是: urls.py

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='registration'),
    url(r'^customer/add/$', views.UserFormView.as_view(), name='customer-add'),

]

我认为post方法无效,因为当我点击提交按钮时,追溯是

'[26/Jul/2017 23:50:37] "GET /customer/add/?csrfmiddlewaretoken=nLX4YAZ1Tk6Zt5DJUJNM9fiYtw91pZwsrDdZwb5tpr80qKBos36eV9SZdR23c9BT&username=dq&email=admin%40c.com&password=password123 HTTP
/1.1" 200 2796
' 

views.py

class UserFormView(View):
    form_class = UserForm
    template_name = 'registration/registration_form.html'

    # display blank form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    # process form data
    def post(self,request):
       form = self.form_class(request.POST)

       if form.is_valid():
           user = form.save(commit=False)

           username = form.cleaned_data['username']
           password = form.cleaned_data['password']
           user.set_password(password)
           user.save()

           # return username if credentials are correct
           user = authenticate(username=username, password=password)

           if user is not None:

                if user.is_active:
                   login(request, user)
                   return redirect('registration:index')
       return render(request, self.template_name, {'form': form})

forms.py

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        labels = {
            "email": "Your Email"
        }
        fields = [
            'first_name',
            'last_name',
            'username',
            'email',
            'password',
         ]

registration_form.html

 {% if error_message %}
     <p><strong>{{ error_message }}</strong></p>
 {% endif %}

 <form class="form-horizontal" action="" method="post">
     {% csrf_token%}
     {% include 'registration/form-template.html' %}
     <div class="form-group">
         <div class="col-sm-offset-2 col-sm-10">
             <button type="submit" class="btn btn-success">Submit</button>
         </div>
     </div>
 </form>

0 个答案:

没有答案