I am trying to add categories in my blog project. So that whenever user post a blog he will add category also but in the select box it is not showing I tried this :
from django import forms
from .models import Post,Category,Comment
choices = Category.objects.all().values_list('name','name')
choice_list = []
for item in choices:
choice_list.append(item)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title','title_tag','author','category','body','snippet','header_image')
widgets = {
'title' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title of the Blog'}),
'title_tag' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title tag of the Blog'}),
'author' : forms.TextInput(attrs={'class':'form-control','value':'','id':'elder','type':'hidden'}),
'category' : forms.Select(choices=choice_list, attrs={'class':'form-control','placeholder':"blog's category"}),
'body' : forms.Textarea(attrs={'class':'form-control','placeholder':'Body of the Blog'}),
'snippet' : forms.Textarea(attrs={'class':'form-control'}),
}
Here Category model contains my categories
My models.py
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(
null=True, blank=True, upload_to="images/")
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=25, default='coding')
snippet = models.CharField(max_length=50)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
# return reverse("article_detail", args={str(self.id)}) return to self blog
return reverse("home")
question from:
https://stackoverflow.com/questions/65937517/adding-choices-but-not-showing-in-the-selectbox 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…