我的表单似乎永远不会将输入从一个模板返回到另一个模板,而且我很难理解为什么。
forms.py:
class textForm(forms.Form):
message = forms.CharField(widget=forms.Textarea)
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .forms import textForm
from django.http import HttpResponseRedirect
# The nbar statement is used to show which one is active
def index(Request):
return render (Request, 'index/home.html')
def article(Request):
if Request.method == 'POST':
form = textForm(Request.POST)
if form.is_valid():
message = form.cleaned_data['message']
form = textForm()
context = {'message': message, 'form': form}
#if request is valid and post, send info to next template
return render(Request, 'index/article.html', context)
else:
form = textForm()
#else return to the template where user fills out input
return render(Request, 'index/translate.html', {'form': form})
def translate(Request):
return render (Request, 'index/translate.html', {'nbar': 'translate'})
def most_popular(Request):
return render (Request, 'index/most_popular.html', {'nbar': 'most_popular'})
def the_news(Request):
return render (Request, 'index/news.html', {'nbar': 'news'})
def sports(Request):
return render (Request, 'index/sports.html', {'nbar': 'sports'})
def science(Request):
return render (Request, 'index/science.html', {'nbar': 'science'})
def politics(Request):
return render (Request, 'index/politics.html', {'nbar': 'politics'})
def funny(Request):
return render (Request, 'index/funny.html', {'nbar': 'funny'})
index / translate.html表单在哪里,用户在哪里输入文本:
{% extends "index/header.html" %}
{% block content %}
<div class="container">
<h5 style="padding-top: 20px; padding-bottom: 40px;"><strong>welcome!</strong></h5>
<form action="/article" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
</div>
{% endblock %}
index / article.html我想从以下形式返回值:
{% extends "index/header.html" %}
{% block content %}
<!-- the first div functionality will be created later -->
<div>
<h2 style="font-size:45px; margin-top: 35px; margin-bottom: -15px;"> article title </h2>
</div>
<div class="card border border-dark" style = "padding-left: 0px;">
<div class="card-body" style="margin-top: -10px; margin-bottom: -10px; margin-left: -10px;">
<p class="card-title"><strong> result:</strong> </p>
<p class="card-text"> {{ message }} </p>
</div>
</div>
{% endblock %}
我得到的结果是第二个HTML文件中的{{message}}始终为空-它不返回任何内容
答案 0 :(得分:0)
模板中的错误。应该是:
<form action="/article" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
并像这样编辑视图:
def article(request):
if request.method == 'POST':
form = TextForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
form = TextForm()
context = {'message': message, 'form': form}
return render(request, 'index/article.html', context)
else:
form = TextForm()
return render(request, 'index/article.html', {'form': form})