我是Django的新手,并且在使用表单方面遇到了一些麻烦。我尝试显示单个文本输入,以便用户可以输入他们的电话号码,然后将其发送到我的电子邮箱。我实际上会将它存储在postgre数据库中,但希望首先获得基础知识。正在显示提交按钮,但文本输入字段不是。我尝试将那些forms.py放在views.py中,看看PhoneForm()函数和文件是否没有导入但是没有做任何事情。
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core.mail import send_mail
from .forms import PhoneForm
# Create your views here.
def index(request):
# Render the index.html template with a context dictionary
return render(request, "index.html")
def get_number(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
#create a form instance
form = PhoneForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['phone_form'],
['siteadmin@example.com'],
)
return HttpResponseRedirect('/thanks/')
else:
form = PhoneForm()
return render(request, 'index.html', {'form': form})
的index.html
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
class PhoneForm(forms.Form):
phone_form = forms.CharField(widget=forms.TextInput())
编辑:添加urls.py(应用中的那个)
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.get_number, name='get_number'),
]
答案 0 :(得分:0)
在index.html
中从{{form}}更改为{{form.phone_form}}答案 1 :(得分:0)
urls.py
中的两个网址都有相同的表达式r'^$'
,django按顺序查找它们,因此将始终选择第一个(索引)。这链接到索引视图而不是get_number视图。这意味着表单不会传递给模板,表单也不会显示。
要解决此问题url(r'^$', get_number),
到&#39; urlpatterns&#39;的顶部。