Django Forms: Hidden model field?

前端 未结 2 1889
盖世英雄少女心
盖世英雄少女心 2021-02-05 08:38

I\'ve got a Form. I want to include a hidden field that returns a model. I\'ll set it\'s value in the view; I just need it to be posted along to the next page.

2条回答
  •  不知归路
    2021-02-05 09:15

    A hidden field that returns a model? So a model instance ID?

    The forms.HiddenInput widget should do the trick, whether on a FK field or CharField you put a model instance ID in.

    class MyForm(forms.Form):
        hidden_2 = forms.CharField(widget=forms.HiddenInput())
        hidden_css = forms.CharField(widget=forms.MostWidgets(attrs={'style': 'display:none;'}))
    

    I suppose the fastest way to get this working is

    class MyForm(forms.Form):
        model_instance = forms.ModelChoiceField(queryset=MyModel.objects.all(), widget=forms.HiddenInput())
    
    form = MyForm({'model_instance': '1'})
    form.cleaned_data['model_instance']
    

    But I don't like the idea of supplying MyModel.objects.all() if you're going to specify one item anyways.

    It seems like to avoid that behavior, you'd have to override the form __init__ with a smaller QuerySet.

    I think I prefer the old fashioned way:

    class MyForm(forms.Form):
        model_instance = forms.CharField(widget=forms.HiddenInput())
    
        def clean_model_instance(self):
            data = self.cleaned_data['model_instance']
            if not data:
                raise forms.ValidationError()
            try:
                instance = MyModel.objects.get(id=data)
            except MyModel.DoesNotExist:
                raise forms.ValidationError()
            return instance
    

提交回复
热议问题