How to hide a field in django modelform?

后端 未结 1 380
萌比男神i
萌比男神i 2021-02-06 09:37

For example:

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

class TestModelForm(ModelForm):
    class Meta         


        
1条回答
  •  执念已碎
    2021-02-06 10:20

    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()
                # ...
    

    0 讨论(0)
提交回复
热议问题