Dynamic queryset for foreignKey in Single Page Application with Django

375 views Asked by At

I have a single page application with AngularJs and Django. On my main page, I get all the forms needed when loading the page. BUT, some fields are dynamically updated.

Let's say I have

class Model1(models.Model):
    pass

class Model2(models.Model):
   model_1 = models.ForeignKey(Model1)

forms:

class Model2Form(forms.ModelForm):
    class Meta:
        model = Model2
        fields = ('model_1', )

My SPA allows me to create instances of Model1 (without reloading the page). I know how to filter the options shown and dynamically add the new instances in the select field BUT, doing so, when the html is first rendered, before angular magic takes place and filter the available options, I get the queryset made by django which is by default model.objects.all(). All right, I'd like to display none of that. I tried to add in the init of my function:

self.fields['model_1'].queryset = Model1.objects.none()

and indeed no option is displayed in the select field when the form is first rendered but then, I can't validate my form, I get the error: Select a valid choice. That choice is not one of the available choices. (obviously, it had no option available due to the queryset.none() )

I'd really like not to load forms when called but doing it when my page first load. Is there any option to help me do so?

Cheers guyz, Keep rocking

2

There are 2 answers

4
Dric512 On

You need to specify that the model_1 field of Model2 can be null, as specified here: Allow null in foreign key to user. Django

model_1 = models.ForeignKey(Model1, null=True, blank=True, default = None)
0
abrunet On

I find out how to handle that problem. It is quite stupid, I did not give you all the parameters of the problem.

The forms are rendered on load but when I validate it, it goes through a CRUD operation and an OTHER form is initialized at this point which will handle the data I'm sending. So I can override the queryset in the init of that (second) form based on some extra kwargs to differentiate between the form I'm using for the first rendering and the form to handle my data.

No need to make any field nullable or add extra validation.

Hope I'm clear enough. Cheers