Django 1.8: access current user (extended) in ForeignKey.limit_choices_to

386 Views Asked by At

UPDATE

I tried to use CuserMiddleware and used it like this to get the current user:

 def limit_by_username():
     c_username = ""
     c_user = CuserMiddleware.get_user()
     if c_user is not None:
         c_username = c_user[0].username
     return {'reviewer__user__username__exact':c_username}

 r_list_of_reviews = models.ForeignKey('Review', blank=True, null=True, limit_choices_to=limit_by_username())    

But still, the list of reviews are not yet displayed Again, any ideas are greatly appreciated.

END UPDATE

I'm using/extending the django Admin site. I'm having a problem in restricting and displaying all the reviews related to a particular reviewer. I've used limit_choices_to and the ThreadLocal.get_current_user() from django_tools, but it's not working, and the review objects for a particular reviewer are not displayed. Below are my models:

class Reviewer(models.Model):
    id = models.AutoField(primary_key=True)
    r_user = models.OneToOneField(User)
    r_list_of_reviews = models.ForeignKey('Review', blank=True, null=True, limit_choices_to={'reviewer__r_user__username__exact': ThreadLocal.get_current_user()})

class Review(models.Model):
    USER_RATING = (
            (1, '1'),
            (2, '2'),
            (3, '3'),
            (4, '4'),
            (5, '5'),
    )
    id = models.AutoField(primary_key=True)
    reviewer = models.ForeignKey('Reviewer')
    review_rating = models.IntegerField(choices=USER_RATING, default=0)

Any ideas on how to do this right? Thanks in advance!

1

There are 1 best solutions below

1
On

You might be having typos in limit_by_username(). Lookup key should probably say 'reviewer__r_user__username__exact', and c_user[0] should be just c_user since according to middleware implementation it can’t be anything list-like.

By the way, you could construct your choices for the field by hooking up into ModelAdmin.get_form(). That method has access to request and thus current user. That would be my choice, and also the more Django-y way compared to thread locals (which is what CuserMiddleware uses).