Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

python - How do I filter values in a Django form using ModelForm?

I am trying to use the ModelForm to add my data. It is working well, except that the ForeignKey dropdown list is showing all values and I only want it to display the values that a pertinent for the logged in user.

Here is my model for ExcludedDate, the record I want to add:

class ExcludedDate(models.Model):
    date = models.DateTimeField()
    reason = models.CharField(max_length=50)
    user = models.ForeignKey(User)
    category = models.ForeignKey(Category)
    recurring = models.ForeignKey(RecurringExclusion)

    def __unicode__(self):
        return self.reason

Here is the model for the category, which is the table containing the relationship that I'd like to limit by user:

class Category(models.Model):
    name = models.CharField(max_length=50)
    user = models.ForeignKey(User, unique=False)

    def __unicode__(self):
        return self.name

And finally, the form code:

class ExcludedDateForm(ModelForm):

    class Meta:
        model = models.ExcludedDate
        exclude = ('user', 'recurring',)

How do I get the form to display only the subset of categories where category.user equals the logged in user?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can customize your form in init

class ExcludedDateForm(ModelForm):
    class Meta:
        model = models.ExcludedDate
        exclude = ('user', 'recurring',)
    def __init__(self, user=None, **kwargs):
        super(ExcludedDateForm, self).__init__(**kwargs)
        if user:
            self.fields['category'].queryset = models.Category.objects.filter(user=user)

And in views, when constructing your form, besides the standard form params, you'll specify also the current user:

form = ExcludedDateForm(user=request.user)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...