inlineformset_factory中的小部件 [英] Widgets in inlineformset_factory

查看:47
本文介绍了inlineformset_factory中的小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我设法制作了inlineformset_factory,但是尽管我在 ModelForm 中指定了它们,但父模型中的小部件却无法正常工作.

Hey i managed to make a inlineformset_factory but my widget in the Parent Model are not working although i have specified them in the ModelForm .

我的forms.py:

My 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无法正常工作....

My CKEditorWidget is not working ....

我的views.py:

My 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时被覆盖了...

I guess that my widget from the Parent model (Post) was overwritten while using a inlineformset_factory...

推荐答案

您可以在inlineformset_factory内部设置小部件.

You can set widgets inside of inlineformset_factory.

PostVocabInlineFormSet = inlineformset_factory(
    Post,
    PostVocab,
    extra=1,
    exclude=(),
    widgets={'post': CKEditorWidget()
)

从Django文档中... inlineformset_factory使用modelformset_factory并将其大部分参数传递给modelformset_factory.这意味着您可以像将其传递给modelformset_factory一样使用widgets参数.

From Django docs...inlineformset_factory uses modelformset_factory and passes most of its arguments to modelformset_factory. This means you can use the widgets parameter in much the same way as passing it to modelformset_factory.

AuthorFormSet = modelformset_factory(
...     Author, fields=('name', 'title'),
...     widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})})`

这篇关于inlineformset_factory中的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆