如何为 Django 中的多对多关系创建内联对象?

How to create objects inline for many to many relationships in Django?

我已经定义了问题和标签之间的这种关系:(这样正确吗?)

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)

我想要一个管理页面来创建 Questions 以及 Tags,所以这是我的 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/ 时,我看到的页面是这样的:

如您所见,它只允许我 select 一个预先存在的标签。但是,我希望能够在创建内联问题时首次 创建 标签。我该怎么做?

谢谢!

不要对标签使用内联。常规 M2M 字段将在管理员中正常工作。要获得更合适的 M2M 小部件,请添加 filter_horizontal 属性:

class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['text', 'tags']}),
    ]
    filter_horizontal = ['tags']
    ...

要从 QuestionAdmin 创建一个 Tag,请按小部件右侧的绿色 + 标志。