django model forms filter queryset

10,824

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)
Share:
10,824
whatf
Author by

whatf

Updated on June 07, 2022

Comments

  • whatf
    whatf almost 2 years

    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?

    • Raunak Agarwal
      Raunak Agarwal over 11 years
      But why wouldn't the options include the Author in the first place?
  • whatf
    whatf over 11 years
    could you please elaborate more with an example.