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

时间:2015-03-03 11:37:50

标签: python django django-models django-admin inline-formset

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

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/时,我看到的页面就是:

enter image description here

如您所见,它只允许我选择预先存在的标记。但是,我希望第一次能够创建标记,同时创建内联问题。我怎么能这样做?

谢谢!

1 个答案:

答案 0 :(得分:2)

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

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

要从Tag创建QuestionAdmin,请按小工具右侧的绿色+符号。