我在问题和标签之间定义了这样的关系:(这是正确的吗?)
myproject / myapp / models.py:
from django.db import models
from django.contrib.auth.models import User
from vote.managers import VotableManager
from django.utils import timezone
from datetime import datetime, timedelta
class Tag(models.Model):
text = models.CharField(max_length = 20)
user = models.ForeignKey(User)
class Question(models.Model):
text = models.TextField()
user = models.ForeignKey(User) # First writer of the question
tags = models.ManyToManyField(Tag)
votes = VotableManager()
created = models.DateTimeField(auto_now_add=True) # auto_now_add=True
modified = models.DateTimeField(auto_now=True) # auto_now=True
def was_published_recently(self):
return self.pub_date >= timezone.now() - timedelta(days=1)
我想要一个管理页面来创建Question
以及Tag
s,所以这是我的admin.py:
from django.contrib import admin
from qportal.models import Tag, Question
class TagsInline(admin.TabularInline):
model = Question.tags.through
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['text']}),
#('Date information', {'fields': ['created'], 'classes': ['collapse']}),
]
inlines = [TagsInline]
list_display = ('text', 'created', 'was_published_recently')
list_filter = ['created']
search_fields = ['text']
admin.site.register(Question, QuestionAdmin)
但是,当我运行runserver
并登录http://127.0.0.1:8000/admin/qportal/question/add/时,我看到的页面就是:
如您所见,它只允许我选择预先存在的标记。但是,我希望第一次能够创建标记,同时创建内联问题。我怎么能这样做?
谢谢!
答案 0 :(得分:2)
不要对标签使用内联。常规M2M
字段可以在管理员中正常使用。要获得更充分的M2M
小部件,请添加filter_horizontal
属性:
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['text', 'tags']}),
]
filter_horizontal = ['tags']
...
要从Tag
创建QuestionAdmin
,请按小工具右侧的绿色+
符号。