我正在尝试在我的博客项目中添加类别。因此,每当用户发布博客时,他也会添加类别,但在选择框中没有显示我试过这个:
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'}),
}
这里类别模型包含我的类别
我的模型.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")