【问题标题】:Django form not getting submitted facing attribute errorDjango表单未提交面临属性错误
【发布时间】:2017-11-13 04:25:49
【问题描述】:

我正在尝试将网络表单中的字段值存储到 django 数据库,下面给出了我的 models.pyviews.py。我面临 AttributeError: 'WSGIRequest' 对象没有属性 'get' * 错误我是 django 和 python 的新手,请在这里告诉我我的错误。

VIEWS.PY

MODEL.PY

【问题讨论】:

  • action='',空的,因为你提交到同一个视图/端点

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


【解决方案1】:

编辑您的视图,

from django.shortcuts import redirect, render

def home(request):
    return render(request, 'home.html')

def index(request):
    if request.method == 'POST':
        form = PageForm(request.POST)
        if form.is_valid():
            form.save()
        #No need to call index view again,
        #it's already been called.
            return redirect('home') #redirection.
    else:
        form = PageForm()
    return render(request, 'index.html', {'form':form})

urls.py

from . import views

url(r'^index/$', views.index, name='index'),
url(r'^home/$', views.home, name='home')

您可以使用render() 快捷功能,

https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

render() 是 1.3 中用于 render_to_response 的全新快捷方式,它将自动使用我从现在开始肯定会使用的 RequestContext。

您的 html 表单中的 action 部分是您定义表单提交的端点或 URL 的地方。由于您的视图接受发布数据,因此您的action='' 需要保持为空,这意味着您将发布到同一个视图本身。

【讨论】:

  • 在我的 index.html 中我应该用什么来做动作部分?单击提交后出现 a404 错误。我应该在哪里重定向页面?
  • 您可能需要编写另一个视图并重定向到该视图,我可以在我的回答中向您展示一个示例
  • 请出示。如果我将其重定向到新视图,则字段值如何保存到 db。我在提交后的 db 中找不到值。
  • 为此,您需要显示您的 forms.py,但请将代码复制粘贴到问题中,不要添加图像链接。我已经更新了我的答案
  • 您只需将action='' 放入模板中即可。
【解决方案2】:

在您的views.py中,上下文部分有错误,{'form':form} 本身就是上下文,无需再次包含'context'并包含请求 render(request,'index.html',{'form':form})

【讨论】:

  • 在我的 index.html 中我应该用什么来做动作部分?单击提交后出现 a404 错误。我应该在哪里重定向页面? – krish 1 分钟前编辑
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 2014-03-13
  • 2019-05-17
  • 2012-03-09
  • 2015-08-23
  • 2017-12-30
相关资源
最近更新 更多