我正在开发具有两种类型用户的Django应用程序:
在后端,两个用户都可以添加匹配报告。管理员可以为每个俱乐部创建报告。我希望记者只有在他是俱乐部的记者时才能选择俱乐部。
内部模特俱乐部是与记者的领域。一位记者可以成为一个或多个俱乐部的记者。
我有去除俱乐部的问题,记者不是俱乐部的记者吗? 如何从组合框中删除一些俱乐部选项?
我试过了:
def get_changeform_initial_data(self, request):
和
def __init__(self, instance, *args, **kwargs):
型号:
class Club(models.Model):
#Id keys
id = models.AutoField(primary_key=True);
#fields
name = models.CharField(max_length=100,verbose_name=_('Name'));
**reporter**=models.ManyToManyField(User,limit_choices_to = {'is_superuser': False}, blank=True,null=True,verbose_name=_('Reporters:'),related_name="reporter_club")
class Report(models.Model):
id = models.AutoField(primary_key=True)
reporter = models.ForeignKey(User, null=True, blank=True, unique=False)
date=models.DateField(_("Date"), blank=False);
league=models.ForeignKey(League, verbose_name=_('League'))
**club1**=models.ForeignKey(Club, related_name='club1',verbose_name=_('Club1') )
如果你看一下图像: link with problem 你可以看到,在club1中列出了所有可能的俱乐部,我只需要将记者定义为记者的俱乐部,而不是全部。
这是我的admin.py for model Reporter:
class MatchReportAdmin(admin.ModelAdmin):
form = PictureFormMatchReport
def get_fieldsets(self, request, obj=None):
fields='date', 'league', 'group'
media_description=('picture',)
#'headline','picture','goals','team_formation','match_report'
return [
(None, {'fields':fields }),
(None, {'fields': (('club1','club2'),), 'classes': ['wide', 'opened']}),
(None, {'fields': (('result1','result2'),('break_result1','break_result2'),)}),
(None, {'fields': ['headline','picture', 'goals','team_formation','match_report']}),
]
list_display = ('custom_date','league','group','reporter','headline','custom_match_report')
list_filter = ('date','league','group','headline')
search_fields = ('date','league__league','group','headline')
save_as = True
def save_model(self, request, obj, form, change):
if not request.user.is_superuser:
reporter = User.objects.get(id=request.user.pk)
obj.reporter=reporter
obj.save()
# Django always sends this when "Save as new is clicked"
if '_saveasnew' in request.POST:
# Get the ID from the admin URL
original_pk = resolve(request.path).args[0]
# Get the original object
original_obj = obj._meta.concrete_model.objects.get(id=original_pk)
# Iterate through all it's properties
for prop, value in vars(original_obj).iteritems():
# if the property is an Image (don't forget to import ImageFieldFile!)
if isinstance(getattr(original_obj, prop), FieldFile):
setattr(obj,prop,getattr(original_obj, prop)) # Copy it!
# find and add reporter pk
reporter = User.objects.get(id=request.user.pk)
obj.reporter=reporter
obj.save()
def get_queryset(self, request):
res = super(MatchReportAdmin, self).get_queryset(request)
if request.user.is_superuser:
return res
return res.filter(reporter=request.user)
admin.site.register(Report,MatchReportAdmin)