Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin form - how to change select options dynamically?

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 has been connected with 1 city. I want him to add news only to the city he id connected with. But superadmin must have possibility to add news to each city. How can I change 'city' field in CityNews, that they show only the city that user is connected with? I can write custom ModelForm but how can I check user_city there and change its queryset?

like image 696
robos85 Avatar asked May 23 '11 22:05

robos85


1 Answers

One obvious way of doing this is to utilize the formfield_for_foreignkey() method on the ModelAdmin.

So if your models.py looks like this:

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)

Then your admin.py could look like this:

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)
like image 105
Rune Kaagaard Avatar answered Sep 29 '22 09:09

Rune Kaagaard