Django admin form - how to dynamically change selection options?

I have 2 models:

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)

My each user is connected to 1 city. I want him to add news only to the city with which he is associated. But a super-admin should be able to add news to every city. How can I change the "city" field in CityNews so that they only show the city the user is associated with? I can write a custom ModelForm, but how can I check user_city there and change its request?

+5
source share
1 answer

One obvious way to do this is to use the formfield_for_foreignkey () method in ModelAdmin.

, 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)
+9

All Articles