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!
You might be having typos in
limit_by_username()
. Lookup key should probably say'reviewer__r_user__username__exact'
, andc_user[0]
should be justc_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 whatCuserMiddleware
uses).