在Django中注册用户

时间:2018-04-24 10:42:22

标签: python html django

我正在创建一个允许用户创建和帐户并查看其个人资料的应用程序。当用户填写注册表单时,他们会被重定向到他们的个人资料。但是,当用户被发送到此页面时,它们将显示为AnonymousUser。以下是我尝试实现该功能的方法。

表单

#Here is the information that a user has to enter to register. All information must be unique. 
class RegisterUserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'input'}))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'input'}))

    class Meta:
        model = User
        fields = ['username', 'email']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'input'}),
            'email': forms.EmailInput(attrs={'class': 'input'}),
        }

        # validate password...
        def clean_password2(self):
            cd = self.cleaned_data
            if cd['password2'] != ['password']:
                raise ValidationError("Passwords don't match")

            return cd['password2']

视图

class RegisterUserView(CreateView):
    form_class = RegisterUserForm
    template_name = "account/register.html"


    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return HttpResponseForbidden()

        return super(RegisterUserView, self).dispatch(request, *args, **kwargs)
#Here i am trying to create the user and save him to the DB
    def form_valid(self, form):
        user = form.save(commit=False)
        user.set_password(form.cleaned_data['password'])
        user.save()
        UserProfileModel.objects.create(user=user)
#Redirecting the new user to the profile page. 
        return HttpResponseRedirect(reverse('account:profile'))

HTML

{% extends 'base.html' %}

{% block body %}
    <div class="container">
        <div class="columns is-mobile">
            <div class="column is-half is-offset-one-quarter">
                <div class="content"><h2>Register</h2></div>
                <form action="{% url 'account:register' %}" method="post">
                    {% csrf_token %}
                    {% for non_field_error in form.non_field_errors %}
                        <p class="help is-danger">{{ non_field_error }}</p>
                    {% endfor %}
                    {% for field in form %}
                        <div class="field">
                            <label for="{{ field.id_for_label }}" class="label">{{ field.html_name }}</label>
                            {{ field }}
                        {% for error in field.errors %}
                            <p class="help is-danger">{{ error }}</p>
                        {% endfor %}
                        </div>
                    {% endfor %}
                    <input type="submit" value="SIGN UP" class="button is-primary">
                </form>
            </div>

        <div class="panel-footer">
            Already have an account?<a href="{% url 'account:login' %}">Click here</a> to login.
        </div>
        </div>
    </div>
{% endblock %}

网址

app_name = 'account'
urlpatterns = [
    url(r'^register/$', view=RegisterUserView.as_view(), name='register'),
    url(r'^login/$', view=LoginUserView.as_view(), name='login'),
    url(r'^logout/$', auth_views.logout, {'next_page': 'account:login'}, name='logout'),

1 个答案:

答案 0 :(得分:1)

您需要在重定向之前登录新用户。为此,您可以使用login方法:

from django.contrib.auth import login

def form_valid(self, form):
        user = form.save(commit=False)
        user.set_password(form.cleaned_data['password'])
        user.save()
        login(self.request, user)
#Redirecting the new user to the profile page. 
        return HttpResponseRedirect(reverse('account:profile'))