【问题标题】:Django 'RequestContext' is not defined - forms.ModelForm未定义 Django 'RequestContext' - forms.ModelForm
【发布时间】:2015-02-05 12:24:40
【问题描述】:

尝试加载我的表单时出现请求上下文错误。

  1. 在我的 models.py 上创建了 ModelForm
  2. 在我的视图上创建了 def add
  3. 链接到视图的网址

views.py

def add_company(request):
# Get the context from the request.
context = RequestContext(request)

# A HTTP POST?
if request.method == 'POST':
    form = CompanyForm(request.POST)

    # Have we been provided with a valid form?
    if form.is_valid():
        # Save the new category to the database.
        form.save(commit=True)

        # Now call the index() view.
        # The user will be shown the homepage.
        return index(request)
    else:
        # The supplied form contained errors - just print them to the terminal.
        print form.errors
else:
    # If the request was not a POST, display the form to enter details.
    form = CompanyForm()

# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render_to_response('add_company.html', {'form': form}, context)

但它卡在视图的第一行。我做的和rango教程一样。它在那里工作。但我的不工作。有人提示吗?

谢谢

请求标头:

Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language de,en-US;q=0.7,en;q=0.3
Cache-Control   max-age=0
Connection  keep-alive
Cookie  csrftoken=I9120vmRATOck4a0SSqlfJPLl62PMUOR; sessionid=isx0p4ezb2y9m129v6243ui3ucuyvrak
Host    localhost:8000
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:33.0) Gecko/20100101 Firefox/33.0

回复:

Content-Type    text/html
Date    Sun, 07 Dec 2014 22:01:03 GMT
Server  WSGIServer/0.1 Python/2.7.6
X-Frame-Options SAMEORIGIN

Request Method:     GET
Request URL:    http://127.0.0.1:8000/comp/new  
Django Version:     1.7.1
Exception Type:     NameError
Exception Value:    

name 'models' is not defined

Exception Location:     /home/mandaro/django/comp/company/forms.py in CompanyForm, line 5
Python Executable:  /usr/bin/python
Python Version:     2.7.6

知道了:

Problem wasn t on form - it was template import problem. Imported render_to_response instead of render solved it. Now it can goes on. ciao and tx

【问题讨论】:

  • 您能否向我们提供您遇到的完整错误?
  • 这与表格无关。这是一个基本的 Python 错误:您尚未导入 RequestContext(来自 django.template)。

标签: python django forms django-forms


【解决方案1】:

你实际上不需要担心传递RequestContext,因为如果你使用render(),它会为你处理它。

所以你会这样做:

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

而不是

return render_to_response('add_company.html', {'form': form}, context)

就是这样。当然,您也需要导入它。

from django.shortcuts import render

希望这能解决你的问题

【讨论】:

  • 否定的。渲染是在视图上导入的。抱歉没有发布完整视图
  • 现在知道了。导入时需要 render_to_response。准正确;)谢谢
  • 值得注意的是,render_to_response 自 django 2.0 起已弃用
【解决方案2】:

您忘记导入 RequestContext 了吗?

from django.template import RequestContext

【讨论】:

    猜你喜欢
    • 2012-10-07
    • 1970-01-01
    • 2021-01-10
    • 2023-01-19
    • 2010-12-02
    • 2011-08-07
    • 2011-08-02
    • 1970-01-01
    • 2011-10-09
    相关资源
    最近更新 更多