Django中的ModelForm

时间:2019-07-28 04:46:58

标签: python django

ModelForm:

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')
    super(ChapterCreateForm, self).__init__(*args, **kwargs)

不起作用 我想添加其他self.field。但这不起作用。

这是我的代码:

class ChapterCreateForm(ModelForm):
    class Meta:
        model = Chapter
        exclude = ('user', 'book',)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(ChapterCreateForm, self).__init__(*args, **kwargs)

    def clean_title(self):
        title = self.cleaned_data['title']
        if Chapter.objects.filter(user=self.user, title=title).exists():
            raise forms.ValidationError('THIS CHAPTER ALREADY WRITTEN')
        return title

但是这种形式有效:

class BookCreateForm(ModelForm):
    class Meta:
        model = Book
        exclude = ('user',)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(BookCreateForm, self).__init__(*args, **kwargs)

    def clean_title(self):
        title = self.cleaned_data['title']
        if Book.objects.filter(title=title).exists():
            if Book.objects.filter(user=self.user, title=title).exists():
                raise forms.ValidationError('YOU WROTE THIS BOOK ')
            raise forms.ValidationError('THIS BOOK ALREADY WRITTEN')
        return title

请帮助我。非常感谢

Screenshot of error

1 个答案:

答案 0 :(得分:0)

您需要通过覆盖类user中的get_form_kwargs,以kwargs形式传递UserCreateChapterView,如下所示:

class UserCreateChapterView(UserPassesTestMixin, CreateView):
    ...
    ...
    def get_form_kwargs(self):
        kwargs = super(UserCreateChapterView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

现在您可以在kwargs.pop('user')的{​​{1}}方法中使用__init__,它应该可以工作。

希望有帮助!