【问题标题】:Unable to display user input in django无法在 django 中显示用户输入
【发布时间】:2017-11-09 14:49:26
【问题描述】:

我是 Django 新手,正在尝试显示用户输入文本。我尝试了多种方法,但到目前为止没有任何效果。需要建议/帮助! 这是我的文件:

models.py

from django.db import models

class Post(models.Model):
    message = models.TextField(max_length=4000)

def __unicode__(self):
    return self.title

views.py

from .models import Post
from django.core.exceptions import *

def index(request):
    return render('index.html')

def result(request):
    p = request.POST['message']
    return render_to_response('result.html', {'message': p}, context_instance=RequestContext(request))

index.html

<!DOCTYPE html>
<head>
    <title>Index page</title>
</head>
<body>
    <div id="header">Welcome to index page</div>
    <div id="content">
        <p>Enter your name</p>
        <form action="/polls/results.html/" method="post" accept-charset="utf-8">{% csrf_token %}
            <input type="text" name="message">
            <input type="submit" value="Send!">
        </form>
    </div>
</body>

结果.html

<!DOCTYPE html>
<head>
    <title>Result page</title>
</head>
<body>
    <div id="header">Here is the result</div>
    <div id="content">
        <p>Your name is: {{ message }}</p>
    </div>
</body>

url.py

from django.conf.urls import include, url
from django.conf.urls.static import static        
from . import views

app_name = 'polls'
urlpatterns = [
   url(r'^$', views.result, name='results'),
 ]

【问题讨论】:

  • 表单操作错误,请添加您的 urls 文件,以便我可以帮助您
  • 哦,是的。添加了 url.py。

标签: python django django-models django-forms django-templates


【解决方案1】:

将您的表单操作编辑为{% url 'result' %},这样它就会像这样

<form action="{% url 'result' %}" ....>
....
....
</form> 

这将生成 URL,您对 url 进行硬编码也是错误的,我们不会在其中添加 .html,顺便说一句,您可以在没有两个两个模板的情况下执行此操作(在同一个 url 中):)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-16
    • 2022-10-04
    • 2014-12-27
    • 2022-11-04
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多