如何在基于类视图的同一页面上处理Django登录和注册?

时间:2014-10-16 05:37:01

标签: django

我想创建一个包含登录和注册表单的页面。根据这个答案:https://stackoverflow.com/a/1395866/2532070,最好的方法是为每个表单使用单独的<form action="{{url}}"标记,并使用两个不同的视图来处理每个表单的POST数据。我的问题是使用相同的视图将允许我将错误传递回表单,但如果我使用单独的URL与单独的URL,我必须将用户重定向回原始页面并将这些参数作为查询的一部分添加字符串,效率似乎不高。

我的网址:

url(r'^$', HomePageView.as_view(), name="home_page"),
url(r'^profile/(?P<pk>\d+)/$', MemberUpdate.as_view(template_name="profile.html"), name="profile_page"),
url(r'^signup/$', SignupUser.as_view(), name="signup_user"),

我的观点:

class HomePageView(TemplateView):
    template_name = "index.html"

    login_form = AuthenticationForm()
    signup_form = UserCreationForm()

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        context['login_form'] = self.login_form
        context['signup_form'] = self.signup_form
        context['signup_action'] = reverse("signup_user")
        return context

class SignupUser(CreateView):
    model = settings.AUTH_USER_MODEL
    form_class = MemberForm
    template_name = "index.html"

    def get_success_url(self):
        return reverse("profile_page", args=[self.object.pk])

    def form_invalid(self, form):

        # here, how do I pass form.errors back to the home_page?
        # I know messages framework is possible but this isn't as
        # easy to add each error to its respective field as 
        # form.errors would be.

        return HttpResponseRedirect(reverse('home_page'))

...我将获得登录表单的POST数据的第三个视图。这是管理我的表单/视图的可接受方式,还是我最好只编写一个整体视图,区分其post方法中的注册和登录表单与if语句?

0 个答案:

没有答案