Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ModelForm instance with custom queryset for a specific field

I have a model not unlike the following:

class Bike(models.Model):     made_at = models.ForeignKey(Factory)     added_on = models.DateField(auto_add_now=True) 

All users may work at a number of factories and therefore their user profiles all have a ManyToManyField to Factory.

Now I want to construct a ModelForm for Bike but I want the made_at list to consist of only factories at which the current user works. The idea is that users should be able to add bikes that they've assembled and enter which of the factories the bike was made at.

How do I do that?

like image 893
Deniz Dogan Avatar asked Nov 30 '09 17:11

Deniz Dogan


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How can we make field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.

Which method has a form instance which runs validation routines for all its fields?

The run_validators() method on a Field runs all of the field's validators and aggregates all the errors into a single ValidationError . You shouldn't need to override this method.


2 Answers

try something like this in the view

form  = BikeForm() form.fields["made_at"].queryset = Factory.objects.filter(user__factory) 

modify the Factory queryset so that it identifies the factory which the user works at.

like image 82
Dave Avatar answered Sep 28 '22 15:09

Dave


You question might be a dupe of this.

S. Lott's answer there is the ticket to solve your problem. He answered:

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.

form.rate.queryset = Rate.objects.filter(company_id=the_company.id) If you take the default ModelForm object, form.fields["rate"].queryset = ...

This is done explicitly in the view. No hacking around.

like image 22
cethegeek Avatar answered Sep 28 '22 15:09

cethegeek