Django 表单不显示

Django form doesn't display

我正在尝试开发一个简单的 Django 应用程序,包含一个联系表单和一个感谢页面。我根本没有使用 Django 'admin';也没有数据库。姜戈 3.2.12。我正在使用 python manage.py runserver

在 localhost 上工作

我无法在 http://127.0.0.1:8000/contact/contact 显示实际表格;我只看到来自 /contact/contactform/templates/contact.html:

的提交按钮

静态文件加载正常:http://127.0.0.1:8000/static/css/bootstrap.css

thanks.html 页面加载正常:http://127.0.0.1:8000/contact/thanks

这是目录结构:

/contact/contact/settings.py

import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()

DEBUG=True

BASE_DIR = Path(__file__).resolve().parent.parent

ALLOWED_HOSTS = ['127.0.0.1'] + os.getenv('REMOTE_HOST').split(',')

SECRET_KEY = os.getenv('SECRET_KEY')
EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS')
EMAIL_HOST = os.getenv('EMAIL_HOST')
EMAIL_PORT = os.getenv('EMAIL_PORT')
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'contactform.apps.ContactformConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'contact.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'contact.wsgi.application'


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]



LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

/contact/contact/urls.py

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

from django.urls import include
urlpatterns += [
    path('contact/', include('contactform.urls')),
]

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

/contact/contactform/urls.py

from django.urls import path
from . import views

app_name = 'contactform'

urlpatterns = [
    path('thanks/', views.thanks, name='thanks'),
    path('contact/', views.contact, name='contact'),
]

/contact/contactform/views.py

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404

from contactform.forms import ContactForm
from contact.settings import EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST_PASSWORD, EMAIL_HOST

def thanks(request):
    return render(request, 'thanks.html', {})

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form_data = form.cleaned_data
            msg = MIMEMultipart()
            msg['From'] = EMAIL_HOST_USER
            msg['To'] = EMAIL_HOST_USER
            msg['Subject'] = f'Personal site: {form_data["subject"]}'
            message = f'Name: {form_data["name"]}\n' \
                      f'Email address: {form_data["email_address"]}\n\n' \
                      f'{form_data["message"]}'
            msg.attach(MIMEText(message))
            with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as server:
                server.ehlo()
                server.starttls()
                server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
                server.sendmail(EMAIL_HOST_USER, EMAIL_HOST_USER, msg.as_string())
            return HttpResponseRedirect('/thanks')
    else:
        form = ContactForm()

    return render(request, 'contact.html')

/contact/contactform/models.py

from django.urls import reverse

/contact/contactform/apps.py

from django.apps import AppConfig

class ContactformConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'contactform'

/contact/contactform/forms.py

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'class': 'form-control', 'maxlength': '100'}
    ))
    email_address = forms.EmailField(required=True, widget=forms.EmailInput(
        attrs={'class': 'form-control', 'maxlength': '100'}
    ))
    subject = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'class': 'form-control', 'maxlength': '100'}
    ))
    message = forms.CharField(required=True, widget=forms.Textarea(
        attrs={'class': 'form-control', 'maxlength': '1000', 'rows': 8}
    ))

/contact/contactform/templates/contact.html

<h2>Form</h2>
    <form action="/contact/" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Send</button>
    </form>

22 年 2 月 20 日更新

这个 views.py 现在可以使用并显示联系表;剩下的问题是当表单完成时,重定向到感谢页面会抛出 404。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from django.shortcuts import redirect
from django.shortcuts import render, get_object_or_404

from contactform.forms import ContactForm
from contact.settings import EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST_PASSWORD, EMAIL_HOST

def thanks(request):
    return render(request, 'thanks.html', {})

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form_data = form.cleaned_data
            msg = MIMEMultipart()
            msg['From'] = EMAIL_HOST_USER
            msg['To'] = EMAIL_HOST_USER
            msg['Subject'] = f'Site Email'
            message = f'Name: {form_data["name"]}\n' \
                      f'Email address: {form_data["email_address"]}\n\n' \
                      f'{form_data["message"]}'
            msg.attach(MIMEText(message))
            with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as server:
                server.ehlo()
                server.starttls()
                server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
                server.sendmail(EMAIL_HOST_USER, EMAIL_HOST_USER, msg.as_string())
            return redirect('contactform:thanks')
    else:
        form = ContactForm()

    return render(request, 'contact.html', { "form": form })

错误屏幕:

form 不会显示,因为您没有将它传递到模板中。您可以在 contact 视图中执行此操作:

return render(request, 'contact.html', {
     'form': form
})

编辑:
如果您收到 'return' outside function 错误,您可以在 contact 视图中执行此操作。

def contact(request):
    form = ContactForm() # Before if condition

您可以删除 else 条件。

编辑 2:
这应该是您的 contact 视图。

def contact(request):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form_data = form.cleaned_data
            msg = MIMEMultipart()
            msg['From'] = EMAIL_HOST_USER
            msg['To'] = EMAIL_HOST_USER
            msg['Subject'] = f'Personal site {form_data["subject"]}'
            message = f'Name: {form_data["name"]}\n' \
                  f'Email address: {form_data["email_address"]}\n\n' \
                  f'{form_data["message"]}'
            msg.attach(MIMEText(message))
            with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as server:
                server.ehlo()
                server.starttls()
                server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
                server.sendmail(EMAIL_HOST_USER, EMAIL_HOST_USER, msg.as_string())
            return HttpResponseRedirect('/thanks')
        else:
            return HttpResponseRedirect(reverse('contactform:contact'))

    return render(request, 'contact.html', {
        'form': form
    })

您的 Django 表单没有显示,因为您没有将表单传递给 html 模板。你必须通过它。

return render(request, 'contact.html','form':form)

试试这个,它应该可以工作:

def contact(request):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form_data = form.cleaned_data
            msg = MIMEMultipart()
            msg['From'] = EMAIL_HOST_USER
            msg['To'] = EMAIL_HOST_USER
            msg['Subject'] = f'Personal site {form_data["subject"]}'
            message = f'Name: {form_data["name"]}\n' \
                  f'Email address: {form_data["email_address"]}\n\n' \
                  f'{form_data["message"]}'
            msg.attach(MIMEText(message))
            with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as server:
                server.ehlo()
                server.starttls()
                server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
                server.sendmail(EMAIL_HOST_USER, EMAIL_HOST_USER, msg.as_string())
            return HttpResponseRedirect('/thanks')
        else:
            return HttpResponseRedirect('contactform:contact')

    return render(request, 'contact.html','form':form)

forms.py

from django import forms
from .models import *

class ContactForm(forms.ModelForm):
      class Meta:
        model = your_model_name
        fields = '__all__' 

之后,您在 Update 2/20/22

更新了项目

您忘记为 url_patterns 列表中的 contactform 应用程序注册默认 path

你的/contact/contact/urls.py

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

from django.urls import include
urlpatterns += [
    path('contact/', include('contactform.urls')),
]

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

应该是:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('contactform.urls'))
]

from django.urls import include
urlpatterns += [
    path('contact/', include('contactform.urls')),
]

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

试试看是否有效?

您必须在主项目的 urls.py 中添加 path('', include('contactform.urls'))

因为,如果我们通过非常简单的测试删除所有内容并通过以下代码更新 views.py

/contact/contactform/views.py

from contactform.forms import ContactForm
from django.http import HttpResponseRedirect
from django.shortcuts import render

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form_data = form.cleaned_data

            return HttpResponseRedirect('/thanks/')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})


def thanks(req):
    return render(req, 'thanks.html')

上面的代码非常有效efficiently.So,我得出的结论是它会起作用。

试一试。

我想强调的一件事是,在制作模板文件时始终使用以下模式。

Appname/templates/Appname/anyfile.html

就像你的情况一样:

contactform/templates/contactform/contact.html

您错过了 templates 之后的第三步,这不是必需的,但如果您这样做了,这是一个很好的做法。

您在 views.py 中重定向时也忘记了 /

应该是return HttpResponseRedirect('/thanks/') 而不是 return HttpResponseRedirect ('/thanks')

另外,去掉form的action属性,使其可以通过HttpResponseRedirect()方法重定向

您的表单操作需要指向

<form action="/contact/contact/"....

或更好

<form action="{% url 'contactform:contact' %}" ...)