Django creation ModelForm with OneToOneField hidden but required

andreihondrari

So I have a model:

class MyThing(models.Model):
    my_field = OneToOneField(SomeOtherModel)

    ... other fields

A form:

class MyThingForm(forms.ModelForm):
    class Meta:
        model = MyThing

A view:

class MyThingView(views.TemplateView):
    template_name = 'thing.html'

    def get(self, request, *args, **kwargs):
        form = MyThingForm()
        return render(self.template_name, {'form': form})

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

        ... retrieve some_instance

        request.POST['my_field'] = some_instance
        form = MyThingForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect(...somewhere else)

        return render(self.template_name, {'form': form})

my thing.html template:

{% for field in form %}
    {{ field }}
{% endfor %}

What my problem is:

  • I need to hide the my_field field when rendering the template (but from backend), that implying that when I do the for on form in the template, it shouldn't have the my_field field in the fields set already
  • This is a creation form, that means that I don't have an existing instance
  • In the backend the my_field is required, so when doing POST I retrieve the instance for my_field from somewhere, doesn't matter where, and add it to the data for the form in sight. After this the form should be valid and can be saved to database

So the basic question is : How do I make a required field, hidden but saveable?

Rohan

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})

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related