[Answered ]-How do I customize the form values in django admin to show only those values that are assigned to him/her?

1👍

You should probably override the formfield_for_foreignkey method in your ModelAdmin for Unit to alter the queryset based on the request. Something like (untested):

class UnitAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'course':
            # filter queryset somehow based on request.user:
            kwargs['queryset'] = db_field.rel.to._default_manager.filter(...) 
        return super(
            UnitAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

1👍

You can use django-smart-select

from smart_selects.db_fields import ChainedForeignKey

example code

from django.db import models
from smart_selects.db_fields import ChainedForeignKey

class Continent(models.Model):
    name = models.CharField(max_length=100)
    def __unicode__(self):
        return self.name

class Country(models.Model):
    name=models.CharField(max_length=100)
    continent=models.ForeignKey(Continent)
    def __unicode__(self):
        return self.name

class Area(models.Model):
    name=models.CharField(max_length=100)
    country=models.ForeignKey(Country)
    def __unicode__(self):
        return self.name

class Location(models.Model):
    continent = models.ForeignKey(Continent)
    country = ChainedForeignKey(
        Country, 
        chained_field="continent",
        chained_model_field="continent", 
        show_all=False, 
        auto_choose=True
    )
    area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country")
    city = models.CharField(max_length=50)
    street = models.CharField(max_length=100)

    def get_products(self):
        return ','.join([p.name for p in self.area.all()])
👤Eswar

Leave a comment