I am trying to show the most frequent tags to select from when adding a post. However, when I added the get_context_data, the form disappeared.
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)
And this is my 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'}),
}
CodePudding user response:
try this
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
Please refer for more details
https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-editing/
CodePudding user response:
You can also override get_form
instead to populate the tags
field of the form with your own queryset like this:
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