DJANGO:如何根据基于类的视图验证多个表单?

时间:2018-03-21 19:21:58

标签: django forms validation

我遇到了一次验证两个表单的问题。请帮帮我。我需要验证字段用户名,但据我了解,我无法将 user_form 传递给form_invalid方法。

class TrainerCreateView(ActiveOnlyMixin, BrandOwnersPermissionMixin, CreateView):
    form_class = TrainerForm
    model = Trainer
    second_form_class = UserCreationForm

    def get_context_data(self, **kwargs):
        context = super(TrainerCreateView, self).get_context_data(**kwargs)
        context['user_form'] = self.second_form_class

    def form_valid(self, form):
        .......

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data(form=form))



from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UserChangeForm

class UserCreationForm(UserCreationForm):
    first_name = forms.CharField(required=True, label='Имя')
    last_name = forms.CharField(required=True, label='Фамилия')

    class Meta:
        model = User
        fields = ("email", "username", "password1", "password2", 'first_name', 'last_name')

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.exclude(pk=self.instance.pk).filter(username=username).exists():
            raise forms.ValidationError(u'Username "%s" is already in use.' % username)
        return username

谢谢!

1 个答案:

答案 0 :(得分:0)

好吧,正如没人知道的那样,我通过改变模型来解决问题,我的意思是form_class和second_form_class。所以,我不能一次验证两个表单,但我可以验证主表单(用户注册详细信息),可能这个信息对某人有用。

{{1}}