I have a many to many relationship between 2 tables Users an Domains. I have defined this relationship in the Domains class. So in the admin interface I see the Users when I am viewing Domains. But I do not see Domains when I am viewing Users. How can I achieve this.
Django管理多对多关系表单
原标题:
问题回答
我知道這是一個較舊的主題,但這是在谷歌上顯示的第一個結果,我認為需要一個更好的答案。
透過這個 Django 錯誤報告,我找到了最好的方法,讓你的多對多欄位在兩個模型中都可以顯示:
class Test1(models.Model):
tests2 = models.ManyToManyField( Test2 , blank=True)
class Test2(models.Model):
tests1 = models.ManyToManyField(Test1, through=Test1.tests2.through, blank=True)
我已经亲自测试过,并且对结果非常满意。
唯一的内置方法是通过InlineModelAdmin,但是您可以使用自定义的ModelForm与您的User ModelAdmin一起创建用于此目的的字段。请参见下面的简化设置代码(假设users = ManyToManyField(related_name= domains )
)。
### yourapp/admin.py ###
from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin.widgets import FilteredSelectMultiple
from .models import Domain
class DomainAdmin(admin.ModelAdmin):
filter_horizonal = ( users ,)
class UserAdminForm(forms.ModelForm):
domains = forms.ModelMultipleChoiceField(
queryset=Domain.objects.all(),
required=False,
widget=FilteredSelectMultiple(
verbose_name=_( Domains ),
is_stacked=False
)
)
class Meta:
model = User
def __init__(self, *args, **kwargs):
super(UserAdminForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields[ domains ].initial = self.instance.domains.all()
def save(self, commit=True):
user = super(UserAdminForm, self).save(commit=False)
user.domains = self.cleaned_data[ domains ]
if commit:
user.save()
user.save_m2m()
return user
class UserAdmin(admin.ModelAdmin):
form = UserAdminForm
admin.site.register(Domain, DomainAdmin)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
我认为您要找的是InlineModelAdmin。
对于仍然遇到这个问题的人们,检查一下https://github.com/kux/django-admin-extend可能是值得的。
它提供了一种机制,在已由其他应用程序定义的ModelAdmin中注入双向多对多字段。
相关问题
热门标签
- winforms
- combobox
- fogbugz
- java
- date
- internationalization
- asp.net
- iis
- url-rewriting
- urlrewriter
- c#
- enums
- ocaml
- haxe
- algorithm
- string
- viewstate
- .net
- c++
- c
- symbol-table
- mysql
- database
- postgresql
- licensing
- migration
- vb.net
- vb6
- declaration
- vb6-migration
- python
- psycopg2
- backup
- vmware
- virtualization
- gnu-screen
- authentication
- desktop
- excel
- xll
- cultureinfo
- regioninfo
- oracle
- client
- session
- download
- html
- virtual
- constructor
- scenarios
- perl
- full-text-search
- javascript
- ajax
- testing
- oop
- inheritance
- vim
- encapsulation
- information-hiding