Python Django ModelForm 有一个隐藏的输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15795869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:02:10  来源:igfitidea点击:

Django ModelForm to have a hidden input

pythondjangodjango-modelsdjango-forms

提问by Modelesq

So I have my TagStatus model. I'm trying to make a ModelForm for it. However, my form requires that the hidden input be populated with the {{ tag.name }}. I've been looking through the docs and I don't know how to make the tag field a hidden input. Perhaps a ModelForm isn't the way to go?

所以我有我的 TagStatus 模型。我正在尝试为它制作一个 ModelForm。但是,我的表单要求使用 {{ tag.name }} 填充隐藏的输入。我一直在查看文档,但不知道如何使标签字段成为隐藏输入。也许 ModelForm 不是要走的路?

models.py:

模型.py:

class TagStatus(models.Model):
    user = models.ForeignKey(User, null=True, unique=True)
    status = models.CharField(max_length=2, choices=tag_statuses)
    tag = models.ForeignKey(Tag, null=True, blank=True)

    def __unicode__(self):
        return self.status

    def save(self, *args, **kwargs):
        super(TagStatus, self).save(*args, **kwargs)

class TagStatusForm(modelForm):
    class Meta:
        model = TagStatus
        fields = ('status','tag') 
        widgets = {
             'select': Select,
             'tag': ???
        }

django views.py:

Django 视图.py:

@login_required
def tags(request):
    all_tags = Tag.objects.all()
    context = base_context(request)
    if request.method == 'POST':
        if 'status_check' in request.POST:
            status_form = TagStatusForm(request.POST)
            #if request.is_ajax():
            if status_form.is_valid():
                status_form.save()
                response = simplejson.dumps({"status": "Successfully changed status"})
            else:
                response = simplejson.dumps({"status": "Error"})
                return HttpResponse (response, mimetype='application/json')
    status_form = TagStatusForm()
    context['status_form'] = status_form
    context['all_tags'] = all_tags
    return render_to_response('tags/tags.html', context, context_instance=RequestContext(request))

template:

模板:

{% for tag in all_tags %}
....
<form class="nice" id="status-form" method="POST" action="">
     {% csrf_token %}
      <input type="hidden" name="status_check" />
      <input type='hidden' name="tag" value="{{ tag.name }}" />
     {{ status_form.status }}
</form>
...
{% endfor %}

How would I go about making a hidden input through a django ModelForm and then populate it through the template?

我将如何通过 django ModelForm 进行隐藏输入,然后通过模板填充它?

采纳答案by Josh

To make a field in a ModelField a hidden field, use a HiddenInput widget. The ModelForm uses a sensible default widget for all the fields, you just need to override it when the object is constructed.

要将 ModelField 中的字段设为隐藏字段,请使用 HiddenInput 小部件。ModelForm 为所有字段使用一个合理的默认小部件,您只需要在构造对象时覆盖它。

class TagStatusForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        widgets = {'tag': forms.HiddenInput()}

回答by Srikar Appalaraju

There are 3 possible ways (AFAIK) to render hidden fields in Django -

有 3 种可能的方法 (AFAIK) 在 Django 中呈现隐藏字段 -

1.You could declare a field normally in forms.pybut in your templates html file use {{ form.field.as_hidden }}

1.您可以正常声明一个字段,forms.py但在您的模板html文件中使用{{ form.field.as_hidden }}

2.in forms.pydirectly use hidden input widget.

2.forms.py直接使用隐藏输入小部件。

class MyForm(forms.Form):
    hidden_field = forms.CharField(widget=forms.HiddenInput())

Once you make the field a hidden input, you could populate the value of the field in templates. Now your hidden field is ready for rendering.

一旦您将该字段设为隐藏输入,您就可以在模板中填充该字段的值。现在您的隐藏字段已准备好进行渲染。

3.Regular form equivalent (thanks to @Modelesq for sharing this nugget). Here no Django is involved. Changes are done at HTML template level. <input type="hidden" name="tag" value="{{ tag.name }}" />

3.等价的正则形式(感谢@Modelesq 分享这个金块)。这里不涉及 Django。更改是在 HTML 模板级别完成的。<input type="hidden" name="tag" value="{{ tag.name }}" />

回答by Lucas B

I was looking for a way to HIDE ALL INPUTS :

我正在寻找一种隐藏所有输入的方法:

class TagStatusForm(forms.ModelForm):
    class Meta:
        model = TagStatus

    def __init__(self, *args, **kwargs):
        super(TagStatusForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget = forms.HiddenInput()

回答by dfrankow

I posted a way to do it with generic class-based views here:

我张贴的方式与普通的基于类的意见做这里

from django.forms import HiddenInput

from django.forms.models import modelform_factory

_patient_create_form = modelform_factory(
    models.Patient,
    fields=['name', 'caregiver_name', 'sex', 'birth_date',
            'residence', 'country'],
    widgets={'country': HiddenInput()})

class PatientCreate(LoginRequiredMixin, UserOrgRequiredMixin, CreateView):
    form_class = _patient_create_form
    template_name = 'healthdbapp/patient_form.html'