2016-06-16 3 views
0

내 프로그램에서 렌더링을 가져 오려고하면 오류가 발생하며 django 1.9에서 지원되지 않기 때문에 오류가 있습니다. python 3.4django 1.9을 사용하고 있습니다.django 이름 렌더링이 정의되지 않았습니다

블로그/조회수 :

from datetime import datetime 
from django.shortcuts import render 

def date_actuelle(request): 
    return render(request, 'blog/date.html', {'date': datetime.now()}) 


def addition(request, nombre1, nombre2): 
    total = int(nombre1) + int(nombre2) 

    # Retourne nombre1, nombre2 et la somme des deux au tpl 
    return render(request, 'blog/addition.html', locals()) 

블로그/URL을 :

from django.conf.urls import url, patterns 
from . import views 

urlpatterns = [ 
    # url(r'^accueil/$', views.home), 
    # url(r'^article/(?P<id_article>\d+)$', views.view_article), 
    # url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})$', views.list_articles), 
    # url(r'^redirection$', views.view_redirection), 
    url(r'^date/$', views.date_actuelle), 
    url(r'^addition/(?P<nombre1>\d+)/(?P<nombre2>\d+)/$', views.addition), 
] 
다음

ImportError: cannot import name render`.

내 코드입니다 : 내 서버를 실행하려고하면 , 나는 오류가

creps_bretonnes.urls :

from django.conf.urls import patterns, include, url 
from django.contrib import admin 
from blog import views 
urlpatterns = [ 
    url(r'^blog/', include('blog.urls')), 
] 

또한 django.shortcuts 가져 오기 *에서 시도했지만 서버가 시작되었지만 페이지에 액세스하려고하면 NameError : name 'render'가 정의되지 않았습니다. 아이디어가 있으십니까? 나는 그것을 실행할 때 서버에 기록 된 어떤

: 8000/블로그/날짜

Environment: 


Request Method: GET 
Request URL: http://localhost:8000/blog/date/ 

Django Version: 1.9.7 
Python Version: 3.4.4 
Installed Applications: 
['django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles'] 
Installed Middleware: 
['django.middleware.security.SecurityMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware'] 



Traceback: 

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in    get_response 
    149.      response = self.process_exception_by_middleware(e, request) 

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response 
    147.      response = wrapped_callback(request, *callback_args, **callback_kwargs) 

File "C:\Users\sperney\Documents\Travail\creps_bretonnes\blog\views.py" in date_actuelle 
    37.  return render(request, 'blog/date.html', {'date': datetime.now()}) 

Exception Type: NameError at /blog/date/ 
Exception Value: name 'render' is not defined 
: django.shortcuts에서 사용하는 경우

cmd values when trying to run the server with from django.shortcuts import render

역 추적은 *와 로컬 호스트에 액세스하려고 가져

는 여기있다 :

""" 
This module collects helper functions and classes that "span" multiple levels 
of MVC. In other words, these functions/classes introduce controlled coupling 
for convenience's sake. 
""" 

from django.template import loader 
from django.http import HttpResponse, Http404 
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect 
from django.db.models.manager import Manager 
from django.db.models.query import QuerySet 
from django.core import urlresolvers 

def render_to_response(*args, **kwargs): 
    """ 
    Returns a HttpResponse whose content is filled with the result of calling 
    django.template.loader.render_to_string() with the passed arguments. 
    """ 
    httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} 
    return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) 

def redirect(to, *args, **kwargs): 
    """ 
    Returns an HttpResponseRedirect to the apropriate URL for the arguments 
    passed. 

    The arguments could be: 

     * A model: the model's `get_absolute_url()` function will be called. 

     * A view name, possibly with arguments: `urlresolvers.reverse()` will 
      be used to reverse-resolve the name. 

     * A URL, which will be used as-is for the redirect location. 

    By default issues a temporary redirect; pass permanent=True to issue a 
permanent redirect 
    """ 
    if kwargs.pop('permanent', False): 
     redirect_class = HttpResponsePermanentRedirect 
    else: 
     redirect_class = HttpResponseRedirect 

    # If it's a model, use get_absolute_url() 
    if hasattr(to, 'get_absolute_url'): 
     return redirect_class(to.get_absolute_url()) 

    # Next try a reverse URL resolution. 
    try: 
     return redirect_class(urlresolvers.reverse(to, args=args, kwargs=kwargs)) 
    except urlresolvers.NoReverseMatch: 
     # If this is a callable, re-raise. 
     if callable(to): 
      raise 
     # If this doesn't "feel" like a URL, re-raise. 
     if '/' not in to and '.' not in to: 
      raise 

    # Finally, fall back and assume it's a URL 
    return redirect_class(to) 

def _get_queryset(klass): 
    """ 
    Returns a QuerySet from a Model, Manager, or QuerySet. Created to make 
    get_object_or_404 and get_list_or_404 more DRY. 
    """ 
    if isinstance(klass, QuerySet): 
     return klass 
    elif isinstance(klass, Manager): 
     manager = klass 
    else: 
     manager = klass._default_manager 
    return manager.all() 

def get_object_or_404(klass, *args, **kwargs): 
    """ 
    Uses get() to return an object, or raises a Http404 exception if the object 
    does not exist. 

    klass may be a Model, Manager, or QuerySet object. All other passed 
    arguments and keyword arguments are used in the get() query. 

    Note: Like with get(), an MultipleObjectsReturned will be raised if more  than one 
    object is found. 
    """ 
    queryset = _get_queryset(klass) 
    try: 
     return queryset.get(*args, **kwargs) 
    except queryset.model.DoesNotExist: 
     raise Http404('No %s matches the given query.' %  queryset.model._meta.object_name) 

def get_list_or_404(klass, *args, **kwargs): 
    """ 
    Uses filter() to return a list of objects, or raise a Http404 exception if 
    the list is empty. 

    klass may be a Model, Manager, or QuerySet object. All other passed 
    arguments and keyword arguments are used in the filter() query. 
    """ 
    queryset = _get_queryset(klass) 
    obj_list = list(queryset.filter(*args, **kwargs)) 
    if not obj_list: 
     raise Http404('No %s matches the given query.' %  queryset.model._meta.object_name) 
    return obj_list 

고마워

+0

1.9에 있어야합니다. https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#render – jonrsharpe

+2

'render' 단축키 **는 장고 1.9에 포함되어 있습니다 ** [docs의 예제] (https : // docs.djangoproject.com/ko/1.9/topics/http/shortcuts/# example')를 참조하십시오. 전체 추적을 게시 할 수 있습니까? 힌트를 줄 수 있습니다. – Alasdair

+0

django.shortcuts 가져 오기 렌더링을 사용할 때 전체 추적을 게시하는 방법을 모릅니다. django.shortcuts import *에서 사용할 때 역 추적을 의미합니까? – StaP

답변

0

Finaly 가상 박스를 사용하여 가상 env (우분투)를 배치했습니다. 나는 우분투 env에이 문제를 전혀 배포하지 않았고 위의 코드와 똑같은 단계를 밟았습니다! 어쨌든 도움 주셔서 감사합니다!

관련 문제