嘿,我设法制作了inlineformset_factory,但是尽管我在ModelForm
中指定了它们,但父模型中的小部件却无法正常工作。
我的forms.py:
class PostForm(forms.ModelForm):
post = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Post
fields = ['title', 'author','picture','post','draft','publish']
class PostVocabForm(forms.ModelForm):
class Meta:
model = PostVocab
exclude = ()
PostVocabInlineFormSet = inlineformset_factory(
Post,
PostVocab,
extra=1,
exclude=(),
)
我的CKEditorWidget无法正常工作....
我的views.py:
class PostPostVocabCreate(CreateView):
model = Post
form_class = PostForm
# fields = ['title', 'author', 'picture', 'post', 'draft', 'publish']
def get_redirect_url(self, pk):
return reverse_lazy('blog:post_detail',
kwargs={'slug': pk},
)
def get_context_data(self, **kwargs):
data = super(PostPostVocabCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['postvocabs'] = PostVocabInlineFormSet(self.request.POST)
else:
data['postvocabs'] = PostVocabInlineFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
postvocabs = context['postvocabs']
with transaction.atomic():
self.object = form.save()
if postvocabs.is_valid():
postvocabs.instance = self.object
postvocabs.save()
return super(PostPostVocabCreate, self).form_valid(form)
我想我的父模型(帖子)中的小部件在使用inlineformset_factory时被覆盖了...
答案 0 :(得分:0)
您可以在inlineformset_factory内部设置小部件。
PostVocabInlineFormSet = inlineformset_factory(
Post,
PostVocab,
extra=1,
exclude=(),
widgets={'post': CKEditorWidget()
)
从Django文档中... inlineformset_factory使用modelformset_factory并将其大多数参数传递给modelformset_factory。这意味着您可以像将其传递给modelformset_factory一样使用widgets参数。
AuthorFormSet = modelformset_factory(
... Author, fields=('name', 'title'),
... widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})})`