如何在Django CBV post方法中验证表单是否有效?

时间:2015-02-13 16:37:59

标签: django validation django-forms django-views django-class-based-views

我有一个自定义注册表单,如下所示:

class AdminSignupForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(AdminSignupForm, self).__init__(*args, **kwargs)
        # remove username from the form (we will autogenerate a random one)
        self.fields.pop('username')

    class Meta:
        # Set this form to use the User model.
        model = User

        # Constrain the UserForm to just these fields.
        fields = ('first_name', 'last_name', 'title', 'email')

    def save(self, commit=True):
        random = ''.join([choice(letters) for i in xrange(30)])
        self.instance.username = random
        return super(AdminSignupForm, self).save()

表单的视图是:

def post(self, request, *args, **kwargs):
    super(AdminSignupView, self).post(request, *args, **kwargs)
    # ... do some things based on the form fields (i.e create object instances, etc.)

    return reverse("home")

我想要做的是验证表单并返回正确的HttpResponse(如果它无效)。问题是我需要在执行某些操作之前调用super(),因为父类post()为我创建了一个User。我想做一些事情,比如从post super()获取返回值并检查它以查看表单是否有效 - 我在django源代码中看到它返回了render_to_response,但它看起来非常难看因为错误。我确信有一个更好的解决方案,但我无法理解它...

1 个答案:

答案 0 :(得分:3)

您是否考虑过使用FormView?

from myapp.forms import AdminSignupForm
from django.core.urlresolvers import reverse
from django.views.generic.edit import FormView

class SignUpView(FormView):
    template_name = 'path/to/signup-template.html'
    form_class = AdminSignupForm
    success_url = reverse("home")

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        return super(SignUpView, self).form_valid(form)

    def form_invalid(self, form):
        # This method is called when invalid form data has been POSTed.
        return super(SignUpView, self).form_invalid(form)

https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#django.views.generic.edit.FormView