I have a few Django models as such:
FirstModel: (has only name and few other fields)
class FirstModel(models.Model):
name = models.CharField(max_length=100)
...
SecondModel: (has services that will relate to FirstModel, this doesn’t have any fks)
class SecondModel(models.Model):
name = models.CharField(max_length=100)
service = models.booleanField(default=False)
...
ThirdModel: (Relates First and Second Models with FKs to both models)
class ThirdModel(models.Model):
first_model = models.ForeignKey(FirstModel, on_delete=models.CASCADE)
second_model = models.ForeignKey(SecondModel, on_delete=models.CASCADE)
I have a view to update the FirstModel, which lists the fields in the First Model, and also include the formset for listing Third model objects related to first model. This is working fine till here.
class UpdateFirstModelView(UpdateView):
model=FirstModel
form_class = FirstModelForm
template_name = "templates/first_model/manage.html"
context_object_name = "first_provider"
def get_context_data(self, **kwargs):
context = super(UpdateFirstModelView, self).get_context_data(**kwargs)
context["first_provider_form"] = context["form"}
context["third_model_formset"] = ThirdModelFormset(queryset=ThirdModel.objects.filter(first_model=self.get_object()), first_model=self.get_object(),)
return context
The formset for third model looks something like this:
class BaseThirdModelFormset(BaseModelFormSet):
def __init__(self, *args, **kwargs):
queryset = kwargs.pop("queryset", ThirdModel.objects.none())
first_model = kwargs.pop("first_model", None)
super().__init__(*args, **kwargs)
self.queryset = queryset
self.extra = 1
for form in self.forms:
if not form.initial:
# Set the initial value for the parent provider field
form.initial["first_model"] = first_model
form.fields["second_model"] = ModelChoiceFieldShowName( # This is a custom function
required=True,
queryset=SecondModel.objects.all(),
empty_label="Add a Second Model Type,
widget=forms.Select(attrs={"class": "form-control"}),
)
ThirdModelFormset = modelformset_factory(
ThirdModel,
fields=["first_model", "second_model"],
formset=BaseThirdModelFormset,
widgets={"first_model": forms.HiddenInput()},
)
Now I want to add a new one to one model for third model, FourthModel. This model will have a few fields.
class FourthModel(models.Model):
name = models.OneToOneModel(ThirdModel, on_delete=models.CASCADE)
...
I want to show a button in the template to set the values of Fourth Model where I show the Third Model. But I can’t seem to send a formset for the FourthModel within the ThirdModelFormset.
I want FirstForm>ThirdForm>FourthForm within the context. Is this possible directly?