【问题标题】:How to show django form in django template?如何在 django 模板中显示 django 表单?
【发布时间】:2021-07-25 02:27:24
【问题描述】:

我正在尝试使用 django 和 css 创建一个表单。

views.py

from django.shortcuts import render
from .forms import ContactForm

def home(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            pass
        else:
            form = ContactForm()
        return render(request, 'home.html', {'form':form})

forms.py

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length = 30)
    email = forms.EmailField(max_length = 254)
    message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here")

def clean(self):
    cleaned_data = super(ContactForm, self).clean()
    name = cleaned_data.get('name')
    email = cleaned_data.get('email')
    message = cleaned_data.get('message')
    if not name and not email and not message:
        raise forms.ValidationError('You have to write something!')

当我尝试将表单添加到我的 html 页面时,如下所示,它没有显示。只显示按钮,没有表单域 -

{% extends 'store/main.html' %}
{% load static %}

{% block content %}
<h3>Store</h3>

<form method = "post" novalidate>
    {% csrf_token %}
    {{ form }}
    <button type='submit'>Submit</button>
</form>
{% endblock content %}

如果我改为使用 css 表单,它显然会以应有的方式显示。

{% extends 'store/main.html' %}
{% load static %}

{% block content %}
<h3>Store</h3>
<form>
    <label for="fname">First Name</label>
    <input type="text" id="fname" name="fname">
    <button type='submit'>Submit</button>
  </form>
{% endblock content %}

所以我决定将表单字段单独添加到 css 表单中。 {{form.name}} 或 {{form.email}} 标签在哪里?

编辑: 嘿 Vivek,联系表格代码是这个 -

class ContactForm(forms.Form):
    name = forms.CharField(max_length = 30)
    email = forms.EmailField(max_length = 254)
    message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here")

html模板是这样的-

{% extends 'store/main.html' %}
{% load static %}
{% block content %}

<h3>Store</h3>


<form method = "post" novalidate>
  {% csrf_token %}
  <label class="float-left" for="name">Name</label>
  {{ form.name }}
    <button type='submit'>Submit</button>
  </form>

  

{% endblock content %}

感谢您的任何意见。

【问题讨论】:

    标签: django django-forms django-templates


    【解决方案1】:

    单独访问表单字段将使您也单独呈现表单错误。 {{form}} 封装了所有内容:- 表单字段、错误、non_field_errors..因此,如果您必须单独访问字段,请不要忘记添加表单错误。

    我已经编写了一个示例代码来实现这个目的。

        {% csrf_token %}
         {% if form.errors %}
      <div class="alert alert-danger"  style="text-align:left">
        <ul>
        {% for field in form %}
            {% for error in field.errors %}
    
                    <li><strong>{{ error|escape }}</strong></li>
    
            {% endfor %}
        {% endfor %}
        {% for error in form.non_field_errors %}
    
                <li><strong>{{ error|escape }}</strong></li>
    
        {% endfor %}
          </ul>
        </div>
    {% endif %}
       <div class="form-row">
            <div class="col-md-4  mb-3">
                <label class="float-left" for="id_name">Name</label>
          {{ form.name }}
            </div>
        <div class="col-md-8 mb-3">
          <label class="float-left" for="id_email">Email ID</label>
          {{ form.email }}
        </div>
      </div>
         <br>
    
       <input type="submit"  class="btn btn-primary" value="Pay" id="submit">
    
      </form>
    

    【讨论】:

    • 谢谢维韦克。您的解释和代码是有道理的,但它对我不起作用。文本和按钮显示,但表单字段不显示。我会尝试在我的主要帖子中添加一张图片,以便您知道它的外观。谢谢。
    • 在我发送给你的代码和你为 ContactForm() 编写代码之后,你能否显示你尝试过的代码
    • 刚刚在主帖中添加了这些代码。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2018-04-07
    • 2017-11-13
    • 2011-02-01
    • 1970-01-01
    • 2014-08-12
    • 2011-01-15
    相关资源
    最近更新 更多