【发布时间】:2023-03-19 00:27:01
【问题描述】:
我是 django 新手,我正在尝试创建一个简单的博客应用程序。
在我的 models.py 中,我为帖子、评论和标签定义了 3 个模型。
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField('post body')
author = models.ForeignKey(User)
pub_date = models.DateTimeField('date published')
is_published = models.BooleanField(default=0)
featured_image = models.CharField(max_length=200)
created_date = models.DateTimeField('date created')
updated_date = models.DateTimeField('date Updated')
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post)
user = models.ForeignKey(User)
comment_text = models.CharField(max_length=200)
created_date = models.DateTimeField('date created')
is_published = models.BooleanField(default=0)
def __str__(self):
return self.comment_text
class Tags(models.Model):
title = models.CharField(max_length=200)
post = models.ManyToManyField(Post)
def __str__(self):
return self.title
如您所见,标签和帖子之间存在多对多的关系。
现在在我的博客模块的管理面板中,我希望用户能够在同一页面上添加帖子、cmets 和标签,即(在创建或更新帖子时)。
我可以成功地为帖子和 cmets 做到这一点, 但是我不知道如何附加标签,以便我可以添加新标签并将它们同时附加到帖子中。我也想为标签字段使用select2 插件。
我的admin.py
from django.core import serializers
from django import forms
from django.http import HttpResponse
from django.utils import timezone
from django.contrib import admin
from .models import Post, Comment, Tags
# Register your models here.
class CommentsInline(admin.StackedInline):
model = Comment
extra = 1
fields = ['comment_text']
class TagsInline(forms.ModelForm):
# I am not sure what should i put in this class
model = Tags
fields = ('title', )
filter_vertical = ('post', )
class PostAdmin(admin.ModelAdmin):
fieldsets = [
('Content', {'fields': ('title', 'body', 'is_published')}),
('Date Information', {'fields': ('pub_date', )})
]
inlines = [CommentsInline, TagsInline]
admin.site.register(Post, PostAdmin)
当尝试运行上面的代码时,我总是看到这个错误:
“blog.Tags”没有“blog.Post”的外键
【问题讨论】:
标签: python django tags django-admin many-to-many