dspjm
dspjm

Reputation: 5830

How to hide a field in django modelform?

For example:

class TestModel(models.Model):
    ref1 = models.ForeignKey(RefModel)
    text1 = models.TextField()

class TestModelForm(ModelForm):
    class Meta:
        model = TestModel
        fields = ('text1')

I only allow the user to input text1 field, but when I redefine the post method of my view, I also want to set the ref1 value, how should I do that?

I wish I can let TestModelForm has the ref1 field but don't let user modify it, then I can modify the value of request.POSt in post method, and pass it to TestModelForm, is that possible?

Upvotes: 11

Views: 16153

Answers (2)

Yousif Al-Zoubi
Yousif Al-Zoubi

Reputation: 16

NOTE: I am using (Django 3.2)

I tried to add a widget and it did not work for me, but I solved it in a simpler way without using widgets.

class TestModelForm(ModelForm):
    ref1 = forms.CharField (widget = forms.Textarea(
        attrs = {
            'hidden': '',
        }
    ))

I hope this helps you or others ;)

Upvotes: 0

ndpu
ndpu

Reputation: 22561

You can use HiddenInput as ref1 widget:

class TestModelForm(ModelForm):
    class Meta:
        model = TestModel
        widgets = {
            'ref1': forms.HiddenInput(),
        }

Another option is saving form with commit argument equal False. This way you can include only visible fields in form and then update model instance with needed data:

def some_view(request):
    # ...
    if request.method == 'POST':
        form = TestModelForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            ref = get_ref_according_to_url()
            instance.ref1 = ref
            instance.save()
            # ...

Upvotes: 19

Related Questions