【发布时间】:2015-04-14 18:38:45
【问题描述】:
我有一个如下所示的自定义注册表单:
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,但搜索错误看起来非常难看那里。我确信有一个更好的解决方案,只是我无法理解它......
【问题讨论】:
标签: django validation django-forms django-views django-class-based-views