我认为最好创建您的 MultipleFormView 类,就像在这个解决方案中一样https://gist.github.com/michelts/1029336
UPD:
抱歉,这不是一个好的解决方案,因为它会验证所有表单。这是一个基于TemplateView的解决方案
class LoginSignupView(TemplateView):
template_name = 'login_signup.html'
redirect_field_name = 'next'
login_prefix = 'login'
signup_prefix = 'signup'
def check_redirect(self, context):
redirect_to = context.get(self.redirect_field_name)
if not redirect_to:
return settings.LOGIN_REDIRECT_URL
netloc = urlparse.urlparse(redirect_to)[1]
if netloc and netloc != self.request.get_host():
return settings.LOGIN_REDIRECT_URL
return redirect_to
def get_context_data(self, *args, **kwargs):
context = super(LoginSignupView, self).get_context_data(*args, **kwargs)
redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')
context[self.redirect_field_name] = redirect_to
context['login_form'] = AuthenticationForm(prefix=self.login_prefix)
context['signup_form'] = UserCreationForm(prefix=self.signup_prefix)
return context
def post(self, request, *args, **kwargs):
context = self.get_context_data(*args, **kwargs)
redirect_to = self.check_redirect(context)
if u'login_submit' in self.request.POST:
login_form = AuthenticationForm(
prefix=self.login_prefix,
data=request.POST
)
if login_form.is_valid():
auth_login(request, login_form.get_user())
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return HttpResponseRedirect(redirect_to)
context['login_form'] = login_form
if u'signup_submit' in self.request.POST:
signup_form = UserCreationForm(
prefix=self.signup_prefix,
data=request.POST
)
if signup_form.is_valid():
# register user
return HttpResponseRedirect(redirect_to)
context['signup_form'] = signup_form
self.request.session.set_test_cookie()
return self.render_to_response(context)