【问题标题】:Django form not rendering in HTMLDjango 表单未在 HTML 中呈现
【发布时间】:2023-03-15 13:00:01
【问题描述】:

我有一个不呈现的表单,我不知道为什么。唯一显示的是提交按钮。我按照hereherehere 描述的方法创建了表单。

我查看了问题的解决方案(在下面列出),但没有帮助。

django-forms not rendering errors

django form not rendering in template. Input fields doesn't shows up

Django Form not rendering

Django Form not rendering - following documentation

html 是 app_core/index.html,它扩展了另一个-landing_page/base.html

html:

{% extends 'landing_page/base.html' %}
{% load i18n %}
{% load staticfiles %}
{% load static %}
{% load bootstrap %}

{%block content %}
<div id="contactus" class="container-fluid">

<br>

<div class="container text-center">

    <div class="row">
        <div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2 text-left">
            <center><h3>{% trans 'Contact Us' %}</h3>
            <p>{% trans 'We are at your disposal 365 days 24 hours a day. When you think of languages think of Milingual.
                            Languages are not studied, they are lived!' %}</p></center>
        </div>
    </div>
    <div class ="row">
        <div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2 text-left">
        <center><h1>Contact Us</h1><center>

        <form id="contactus-form" action="{% url 'contact' %}"method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ form.as_p }}

            <br/>
            <div class="form-actions">
              <button type="submit" class="btn btn-primary pull-center">Send</button>
            </div>
        </form>
        <div>

    </div>

</div>


{%endblock content %}

Views.py

from django.core.mail import BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
#ContactUs
def contact(request):
    if request.method == 'GET':
    form = ContactForm()
else:
    form = ContactForm(request.POST)
    if form.is_valid():
        whoareyou = form.cleaned_data['whoareyou']
        name = form.cleaned_data['name']
        phone_number = form.cleaned_data['phone_number']
        subject = form.cleaned_data['subject']
        from_email = form.cleaned_data['from_email']
        message = form.cleaned_data['message']
        try:
            send_email(subject, message, whoareyou, from_email, ['thiswaysouth@gmail.com'])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect('success')
return render(request, "/index.html", {'form': form})


def success(request):
    return HttpResponse('Success! Thank you for your message.')

form.py

from django import forms


class ContactForm(forms.Form):
    WHOAREYOU_CHOICES = (
        ('Teacher', 'Teacher'),
        ('Student', 'Student'),
        ('Venue', 'Venue'),
        ('Business', 'Business'),
        ('Other', 'Other')
    )
    whoareyou = forms.ChoiceField(choices=WHOAREYOU_CHOICES, required=True)
    name = forms.CharField(required=True)
    phone_number = forms.CharField(required=True)
    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)

还有 urls.py

from django.conf.urls import url, include
from .views import *
from app_core import views

urlpatterns = [
    url(r'^$', IndexPage, name='index'),
    # setting session city
    url(r'^get-city-session$', GetCitySession, name='get-city-session'),
    url(r'^set-city-session$', SetCitySession, name='set-city-session'),
    url(r'^contact/$', views.contact, name='contact'),
    url(r'^success/$', views.success, name='success'),
]

【问题讨论】:

    标签: html django forms


    【解决方案1】:

    您需要将代码放在块中,否则在扩展时它不知道将其放在哪里。在您的 base.html 中,您可以执行类似

    的操作
    {% block body %}
    {% endblock %}
    

    然后在您的 index.html 页面中,您需要围绕您希望在您的基地的那个位置出现的所有内容。

    {% block body %}
      ... Code goes here ...
    {% endblock %}
    

    【讨论】:

    • 它已经在一个 in 块中。我忽略了在这里添加它。 html 的其余部分呈现完美。只是不是的形式
    【解决方案2】:

    这最终得到了一个非常简单的解决方案,但由于我对编程的天真和新奇,我没有注意到它。上面的代码过去和现在都是完全正确的,但是我忽略了在 form.py 的 ContactForm 代码中添加关键的代码行。在表格的最后,我只是简单地添加了以下几行,它完美呈现:

    class ContactForm(forms.Form):
        WHOAREYOU_CHOICES ...
    
        class Meta:
            fields =('whoareyou','name','phone_number','from_email','subject','message')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 2018-08-31
      • 2016-06-02
      • 1970-01-01
      • 2020-02-05
      相关资源
      最近更新 更多