Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django model forms filter queryset

I have the following model:

class Article(models.Model):

   title = models.CharField()
   description = models.TextField()
   author = models.ForeignKey(User)


class Rating(models.Model):

    value = models.IntegerField(choices=RATING_CHOICES)
    additional_note = models.TextField(null=True, blank=True)
    from_user = models.ForeignKey(User, related_name='from_user')
    to_user = models.ForeignKey(User, related_name='to_user')
    rated_article = models.ForeignKey(Article, null=True, blank=True)
    dtobject = models.DateTimeField(auto_now_add=True)

Based upon the above model, i have created a model form, as follows:

Model Forms:

class RatingForm(ModelForm):

     class Meta:
          model = Rating
          exclude = ('from_user', 'dtobject')

Excluding from_user because the request.user is the from_user.

The form renders well, but in to_user in the dropdown field, the author can rate himself as well. So i would want the current_user's name to populate in the dropdown field. How do i do it?

like image 739
whatf Avatar asked Jan 15 '23 22:01

whatf


1 Answers

Override __init__ to remove current user from the to_user choices.

Update: More Explanation

ForeignKey uses ModelChoiceField whose choices are queryset. So in __init__ you have to remove the current user from to_user's queryset.

Update 2: Example

class RatingForm(ModelForm):
    def __init__(self, current_user, *args, **kwargs):
        super(RatingForm, self).__init__(*args, **kwargs)
        self.fields['to_user'].queryset = self.fields['to_user'].queryset.exclude(id=current_user.id)

    class Meta:
        model = Rating
        exclude = ('from_user', 'dtobject')

Now in the view where you create RatingForm object pass request.user as keyword argument current_user like this.

form = RatingForm(current_user=request.user)
like image 168
Rag Sagar Avatar answered Jan 25 '23 16:01

Rag Sagar