2014-12-07 4 views
3

У меня возникла ошибка контекста запроса при попытке загрузить мою форму.Django 'RequestContext' не определен - forms.ModelForm

  1. Создан ModelForm на моем models.py
  2. созданный Защиту добавить на мой взгляд
  3. связанный URL с видом

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 

GOT его:

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 
+0

Можете ли вы предоставить нам полную ошибку вы получили? – smarber

+0

Это не имеет никакого отношения к форме. Это основная ошибка Python: вы не импортировали RequestContext (из django.template). –

ответ

5

вы на самом деле не нужно беспокоиться о прохождении 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 

Надежда, это решает вашу проблему

+0

отрицательный. рендер импортируется на представление. извините за то, что не опубликовал весь обзор – oranj33

+0

получил его сейчас. требуется render_to_response для импорта. quasi right;) спасибо – oranj33

+0

Стоит отметить, что ['render_to_response'] (https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response) устарел, поскольку django 2.0 –

3

Вы забыли импортировать RequestContext?

from django.template import RequestContext 
Смежные вопросы