ModelForm:
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ChapterCreateForm, self).__init__(*args, **kwargs)
Not working I wanna add self.field
other. But it not working.
This is my code:
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
But this form it's working:
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
Please help me. Thanks so much
You need to pass user
in the form kwargs by overriding get_form_kwargs
in the class UserCreateChapterView
as below:
class UserCreateChapterView(UserPassesTestMixin, CreateView):
...
...
def get_form_kwargs(self):
kwargs = super(UserCreateChapterView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
Now you can use kwargs.pop('user')
in the __init__
method of ChapterCreateForm
and it should work.
Hope it helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.