开发者

How to make models connected via ManyToMany relationship editable in two places at the same time in Django admin?

I have two models - News and Subject. News model has a ManyToManyField related to Subject, like that:

subjects = models.ManyToManyField(NewsSubject, verbose_name=u'Subjects', blank=True,null=True,related_name='news')

And I need to have an ability not only to choose Subjects for News in admin, but also to choose News while editing Subject.

I'd started from creating model form:

class NewsSubjectForm(forms.ModelForm):

    news = ModelMultipleChoiceField(queryset=News.objects.all(), 
        label="News", 
        required=False,
        #initial=News.objects.all(),
    )
开发者_开发技巧
    class Meta:
        model = NewsSubject

Here is the question - how I should specify initial values for news according to reverse many-to-many relationship? And how to add a plus button for simple adding?


I am not sure that it can meet your needs but i've done something similar by using TabularInline. Somethink like this should work (i didn't test the following code).

class Subject(models.Model):
    ...

class News(models.Model):
    subject = models.ManyToManyField(Subject, through="NewsSubject")

class NewsSubject(models.Model):
    news = models.ForeignKey(News)
    subject = models.ForeignKey(Subject)  

class NewsOfSubjectInline(admin.TabularInline):
    model = NewsSubject
    raw_id_fields = ('news',)

class SubjectAdmin(admin.ModelAdmin):
    inlines = [NewsOfSubjectInline,]

class SubjectOfNewsInline(admin.TabularInline):
    model = NewsSubject
    raw_id_fields = ('subject',)

class NewsAdmin(admin.ModelAdmin):
    inlines = [SubjectOfNewsInline,]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜