foreign keys for specific primary key django forms
<p>I have class Company, Driver and Car</p>

<pre><code>class Company(models.Model):
title = models.CharField(max_length=256)
...

Class Car(models.Model):
...
company = ForeignKey('Company')    

class Driver(models.Model):
...
company = ForeignKey('Company')
company_car = OneToOneField('Car')
</code></pre>

<p>Also I have GenericView for Create and Update driver, and generic form.</p>

<p>I need form where when user select the company, company_car dropdown consist only Foreign Keys car objects for this company. I know about object_set feature and that`s trick possible with AJAX. But I have no idea how it realize</p>

<p>On your form field, you can specify a query set for the ModelChoiceField. You haven't given your form, but it could look something like this:</p>

<pre><code>class MyForm(ModelForm):
    def __init__(self, *args, **kwargs):
        self.fields['car'] = ModelChoiceField(
          queryset = Car.objects.filter(company=company)
        )
</code></pre>

<p>Documentation is here: <a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield</a></p>

python ajax django django-forms