jeff
jeff

Reputation: 13643

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

I have defined such a relation between questions and tags : (is this correct?)

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)

and I want an admin page to create Questions, as well as Tags, so this is my 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)

however, when I run runserver and login to http://127.0.0.1:8000/admin/qportal/question/add/, the page I see is this :

enter image description here

As you can see, it only allows me to select a pre-existing tag. However I want to be able to create a tag for the first time, while creating the question, inline. How can I do that?

Thanks !

Upvotes: 0

Views: 1673

Answers (1)

catavaran
catavaran

Reputation: 45555

Don't use the inline for the tags. Regular M2M field will work in admin just fine. For more adequate M2M widget add the filter_horizontal property:

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

To create a Tag from the QuestionAdmin press the green + sign at the right side of the widget.

Upvotes: 2

Related Questions