【问题标题】:Show most frequent tags in Django CreateView在 Django CreateView 中显示最常见的标签
【发布时间】:2021-11-20 08:57:44
【问题描述】:

我试图在添加帖子时显示最常见的标签以供选择。但是,当我添加 get_context_data 时,表单消失了。

class AddPostView(CreateView):
    model = Post
    form_class = AddPostForm
    template_name = 'add_post.html'

    def get_context_data(self, **kwargs):
        common_tags = Post.tags.most_common()[:4]
        context = {
            'common_tags': common_tags
        }
        return context

    # gets the user id
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

这是我的表格

class AddPostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title','summary', 'body', 'header_image', 'category', 'tags')

        labels = {
        "title": "العنوان",
        "tags": "العلامات",
        "category": "التصنيف",
        "summary":"الملخص",
        "body": "المحتوى",
        "header_image": "الغلاف",
        }

        widgets = {
            'title': forms.TextInput(attrs={'class':'form-control'}),
            'tags': forms.TextInput(attrs={'class':'form-control'}),
            'category': forms.Select(choices=choices_list, attrs={'class':'form-control'}),
            'summary': forms.TextInput(attrs={'class':'form-control'}),
            'header_image': forms.FileInput(attrs={'class':'form-control'}),
            'body': forms.Textarea(attrs={'class':'form-control'}), 
        }

【问题讨论】:

    标签: python django django-views django-forms django-queryset


    【解决方案1】:

    您也可以覆盖get_form,以使用您自己的查询集填充表单的tags 字段,如下所示:

    class AddPostView(CreateView):
        ...
        def get_form(self, *args, **kwargs):
            form = super().get_form(*args, **kwargs)
            form.fields['tags'].queryset = Post.tags.most_common()[:4]
            return form
    

    【讨论】:

      【解决方案2】:

      试试这个

      class AddPostView(CreateView):
          model = Post
          form_class = AddPostForm
          template_name = 'add_post.html'
      
          def get_context_data(self, **kwargs):
              ctx = super(AddPostView, self).get_context_data(**kwargs) # add this 
              common_tags = Post.tags.most_common()[:4]
              context = {
                  'common_tags': common_tags
              }
              return context
      

      详情请参考

      https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-editing/

      【讨论】:

        猜你喜欢
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-06
        • 1970-01-01
        • 2013-07-06
        • 1970-01-01
        • 2016-11-30
        相关资源
        最近更新 更多