views:

19

answers:

1

Hello!

I have something like this in my model:

class Artykul(models.Model):

id = models.AutoField(max_length = 5, primary_key = True)
tytul = models.CharField(max_length = 255)

kategoria = models.ManyToManyField(Title, limit_choices_to = choices_limit)


dodano = models.DateField(auto_now_add = True)
autor = models.CharField(max_length = 255)
glowny_obrazek = models.ImageField(blank = True, upload_to="uploads/artykul_main_img")

tresc = PlaceholderField('tresc')



def show_categories(self):
    return ', '.join( self.kategoria.values_list('title', flat=True) )

def prepare_choices_limit(self):
    return {'page__level__exact': 1}

def __unicode__(self):
    return self.tytul

As you can see I have var choices_limit in my ManyToManyField. I'd like to make it dynamic to allow certain users to have diffirent options based on their permissions. I can do it by functions prepare_choices_limit(). Question is: if this whole idea is good and if its not how to achieve this effect in diffirent way? Or if its good how can I call this function each time user is logging to admin panel. I dont want it to be called each time Model is called, because I dont need to make permission check for normal users of site, just for administrators.

Thanks in advance Michał

A: 
class Artykuladmin(models.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        formfield= super(ArtykulAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    if request.user.is_superuser:
        return formfield

    if db_field.name == "kategoria":
        #specify your criteria here:
        qs = Title.objects.filter(page__level__exact=1)
        kwargs["queryset"] = qs

    return db_field.formfield(**kwargs)
lazerscience
After few modifications it works perfectly:) tyvm
inc0