Django ModelForm具有隐藏的输入


71

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

models.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:

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

模板:

{% 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 %}

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

Answers:


124

要将ModelField中的字段设为隐藏字段,请使用HiddenInput小部件。ModelForm对所有字段都使用了明智的默认小部件,您只需要在构造对象时覆盖它即可。

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

81

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

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

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

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

将字段设为隐藏输入后,可以在模板中填充该字段的值。现在,您的隐藏字段已准备好呈现。

3.等效于常规形式(感谢@Modelesq共享此块)。这里没有涉及Django。更改在HTML模板级别完成。<input type="hidden" name="tag" value="{{ tag.name }}" />


13
我该如何填充呢?它的常规形式等效如下:<input type="hidden" name="tag" value="{{ tag.name }}" />
Modelesq

您找到填充方法了吗?使用{{ tag.name }}似乎无效。我自己需要{{ forloop.counter }}……
Ehvince

4
您是否有可能添加事物的模板面?
博诺2015年

2

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

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

1

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

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'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.