Django - 分别打印每个型号/表格

时间:2015-07-29 15:43:31

标签: django django-models django-forms django-templates django-views

我使用{{form}}打印出整个表单。我想知道有没有办法分别打印每个元素?我尝试了{{survey.location}}或{{survey.get_location_display}},但它不起作用。以下是models.py,forms.py,views.py和home.html。

models.py

from django.db import models

class Survey(models.Model):
    location = models.CharField(max_length=120, blank=False, null=True)
    education = models.CharField(max_length=120, blank=False, null=True)

forms.py

from django import forms
from .models import Survey
    class Meta:
        model = Survey
        fields = ["location", "education"]

views.py

from django.shortcuts import render
from .forms import SurveyForm

def homepage(request):
    if request.method == 'POST':
        form = SurveyForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
    else:
        form = SurveyForm()
    return render(request, "home.html", {"form": form})

home.html的

<form method='POST' action= "" >{% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Submit"/>    
</form>

2 个答案:

答案 0 :(得分:1)

您可以使用{{form.field_name}}分别打印表单的每个字段。

来自rendering fields manually:

上的Django文档
  

每个字段都可以使用{{ form.name_of_field }}作为表单的属性,并且在Django模板中,将呈现   适当。

{{form.location}} # renders 'location' field of a form

{{form.education}} # renders 'education' field of a form
模板中的

{{form.location}}将呈现如下内容:

<input type="text" name="location" maxlength="120" ../>

答案 1 :(得分:1)

是的,这是docs的一种方式:

<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.subject.errors }}
        <label for="id_subject">Email subject:</label>
        {{ form.subject }}
    </div>
    <div class="fieldWrapper">
        {{ form.message.errors }}
        <label for="id_message">Your message:</label>
        {{ form.message }}
    </div>
    <div class="fieldWrapper">
        {{ form.sender.errors }}
        <label for="id_sender">Your email address:</label>
        {{ form.sender }}
    </div>
    <div class="fieldWrapper">
        {{ form.cc_myself.errors }}
        <label for="id_cc_myself">CC yourself?</label>
        {{ form.cc_myself }}
    </div>
    <p><input type="submit" value="Send message" /></p>
</form>