Django管理表单 - 如何动态更改选择选项?

时间:2011-05-23 22:17:52

标签: django django-admin django-forms

我有2个型号:

class City(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50)


class CityNews(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)
    add_date = models.DateTimeField(auto_now=False, auto_now_add=True, editable=False)
    content = models.TextField()
    city = models.ForeignKey(City)

我的每个用户都与1个城市相关联。我希望他只将新闻添加到他所连接的城市。但是,superadmin必须有可能向每个城市添加新闻。 如何更改CityNews中的“城市”字段,它们只显示用户所连接的城市?我可以编写自定义ModelForm但是如何在那里检查user_city并更改其查询集?

1 个答案:

答案 0 :(得分:9)

这样做的一个显而易见的方法是在ModelAdmin上使用formfield_for_foreignkey()方法。

所以如果你的models.py看起来像这样:

from django.db import models
from django.contrib.auth.models import User

class City(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class CityNews(models.Model):
    added_by = models.ForeignKey(User)
    city = models.ForeignKey(City)
    title = models.CharField(max_length=100)
    content = models.TextField()

class UserExtra(models.Model):
    user = models.ForeignKey(User)
    city = models.ForeignKey(City)

然后你的admin.py看起来像这样:

from django.contrib import admin
from formtesting.models import City, CityNews, UserExtra
from django.forms.models import ModelChoiceField
from django.contrib.auth.models import User

class CityAdmin(admin.ModelAdmin):
    pass

admin.site.register(City, CityAdmin)

class CityNewsAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "city":
            if request.user.is_superuser:
                queryset = City.objects.all()
            else:
                queryset = City.objects.filter(userextra__user=request.user)
            return ModelChoiceField(queryset, initial=request.user)
        elif db_field.name == "added_by":
            if request.user.is_superuser:
                queryset = User.objects.all()
            else:
                queryset = User.objects.filter(id=request.user.id)
            return ModelChoiceField(queryset, initial=request.user)
        else:
            return super(CityNewsAdmin, self).formfield_for_foreignkey(db_field, 
                                                              request, **kwargs)

admin.site.register(CityNews, CityNewsAdmin)

class UserExtraAdmin(admin.ModelAdmin):
    pass

admin.site.register(UserExtra, UserExtraAdmin)