[Django]-Django creation ModelForm with OneToOneField hidden but required

5πŸ‘

βœ…

It very usual use case look at this doc.

In summary you can exclude the field from form and save it after retrieving it from somewhere.

Update code as

class MyThingForm(forms.ModelForm):
    class Meta:
        model = MyThing
        exclude = ['my_field', ]

class MyThingView(views.TemplateView):

    ...
    def post(self, request, *args, **kwargs):

        form = MyThingForm(request.POST)
        #retrieved_my_field = retrieve the field

        if form.is_valid():
            inst = form.save(commit=False)
            inst.my_field = retrieved_my_field
            inst.save()
            return HttpResponseRedirect(...somewhere else)

        return render(self.template_name, {'form': form})
πŸ‘€Rohan

Leave a comment