如何通过HttpResponseRedirect将绑定表单作为上下文传递给TemplateView

时间:2016-09-16 14:20:39

标签: django django-forms django-views

我正在尝试使用TemplateView在一个页面上放置多个帐户管理表单,如下所示:

class AccountManagement(TemplateView):
    """ Generic view to display the account management template """

    template_name = 'accountmanagement.html'

    def get_context_data(self, **kwargs):
        context = super(AccountManagement, self).get_context_data(**kwargs)
        context['user'] = self.request.user
        # pass unbound form instances to context 
        # if there aren't bound instances already there
        if context.get('usercreate_form') is None:
            context['usercreate_form'] = UserCreateForm()
        if context.get('password_form') is None:
            context['password_form'] = PasswordChangeForm()
        return context

我正在使用FormView处理UserCreation(因为此示例已简化;我还需要一些非模型数据和CreateView needs a ModelForm)。此视图处理POST请求,并且应该使用成功消息 重定向到TemplateView,或者将无效的绑定表单传递回上下文,以便模板可以呈现错误。 麻烦的是,它没有用粗体斜体表示(显然HttpResponseRedirect没有通过上下文)。为什么?如何将绑定的表单返回到TemplateView上下文中,以便form.errors可用,用户不必重新键入数据?

class UserCreate(FormView):
    """
    Generic view to create a User.
    """
    form_class = UserCreateForm
    http_method_names = ['post',]
    success_url = reverse_lazy('accountmanagement')
    failure_url = reverse_lazy('accountmanagement')

    def form_valid(self, form):
        #password1 == password2 as per UserCreateForm.clean()
        try:
            new_user = User.objects.create_user(
                username=form.cleaned_data['email'],
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password1']
            )
            new_user.save()
            messages.success(self.request, new_user.username + str(_(": successfully saved.") ))
            return HttpResponseRedirect(self.success_url)
        except IntegrityError:
            #duplicate username
            messages.error(self.request, _("Duplicate email address."))
            return HttpResponseRedirect(self.failure_url, {'usercreate_form': form})

    def form_invalid(self, form):
        messages.error(self.request, _("Unable to create user."))
        return HttpResponseRedirect(self.failure_url, {'usercreate_form': form})

模板:

<form method="post" action="{% url 'usercreate' %}">{% csrf_token %}
{{ usercreate_form.errors }}
{{ usercreate_form.as_p }}
<button type="submit">{% trans 'Save' %}</button>

最后的相关问题:是在TemplateView一页上放置几个相关表单的正确方法吗?然后使用POST处理非模型表单 - 仅FormView并重定向回TemplateView?或者我应该采用不同的方式吗?

0 个答案:

没有答案