Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

Problemas com rotas

Estou assistindo a aula 2, e ao tentar configurar a rota explicada lá (perfis.views.index) estou recebendo um erro ao tentar inicializar o servidor.

Eis o erro:

luizgustavoss@asus ~/Dev/Workspaces/django/connectedin $ python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x7f8ebda2cc08>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/luizgustavoss/Dev/Workspaces/django/connectedin/connectedin/urls.py", line 21, in <module>
    url(r'^$', 'perfis.views.index'),
  File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 85, in url
    raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().

Este é o conteúdo do arquivo urls.py:

"""connectedin URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', 'perfis.views.index'),
]

Este é o conteúdo do arquivo views.py (no projeto perfis):

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    return HttpResponse('Bem-vindo ao ConnectedIn!')

Quando removo a linha:

url(r'^$', 'perfis.views.index'),

do mapeamento da rota, o servidor sobe normalmente. Estou usando o Django 1.11.2 e o Sublime.

3 respostas

Continuei assistindo aos vídeos, e cheguei ao ponto em que se separam os arquivos de configuração de rotas. No arquivo connectedin/urls.py mantive esta configuração:


from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('perfis.urls'))
]

Já no arquivo perfis/urls.py mantive a configuração:


from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^$', 'perfis.views.index'),
]

No entanto ainda não consigo executar o servidor. O seguinte erro é apresentado:

luizgustavoss@asus ~/Dev/Workspaces/django/connectedin $ python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x7f2b5d395c08>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/luizgustavoss/Dev/Workspaces/django/connectedin/connectedin/urls.py", line 8, in <module>
    url(r'^', include('perfis.urls'))
  File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/luizgustavoss/Dev/Workspaces/django/connectedin/perfis/urls.py", line 6, in <module>
    url(r'^$', 'perfis.views.index'),
  File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 85, in url
    raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().

Sou novo em Python e acredito que este erro possa ter relação com a versão do Django que instalei, que é um pouco mais recente do que a que é apresentada pelo instrutor. Se for este o caso é bem frustrante, pois pra mim indica a impossibilidade de trabalhar com uma versão mais recente do Django no curso sem passar por problemas, e que mesmo que eu instale a versão indicada no curso, não conseguirei depois atualizar a versão do framework em meu ambiente sem passar por problemas ou ter que ler a documentação atrás do que está errado.

Se eu mantenho o arquivo connectedin/urls.py da seguinte forma:


from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

o servidor sobe normalmente.

Se tento colocar a declaração da rota do projeto perfis de outra forma (sem as aspas):


from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include(perfis.urls))
]

obtenho o seguinte erro:

luizgustavoss@asus ~/Dev/Workspaces/django/connectedin $ python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x7f6542152c08>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/luizgustavoss/Dev/Workspaces/django/connectedin/connectedin/urls.py", line 8, in <module>
    url(r'^', include(perfis.urls))
NameError: name 'perfis' is not defined
solução!

Depois de alguma pesquisa consegui resolver o problema.

Primeiramente exclui todo o projeto e comecei do zero. Instalei o pip3 para o Python 3:

$ sudo apt-get install python3-pip

Depois instalei o Django através dele:

$ sudo pip3 install django==1.11.2

Criei o projeto e a aplicação para o Python 3:

$ django-admin.py startproject connectedin
...
$ python3 manage.py migrate
...
$ python3 manage.py runserver

O servidor foi executado normalmente. Depois ajustei os arquivos de rotas do projeto conforme indicado, porém com algumas mudanças decorrentes da versão do Django (após a versão 10 existem diferenças de imports e pacotes depreciados que não existem mais). Assim ficaram os arquivos.

connectedin/urls.py:

from django.conf.urls import *
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('perfis.urls'))
]

perfis/urls.py:

from django.conf.urls import *
from perfis import views as perfis_views

urlpatterns = [
    url(r'^$', perfis_views.index, name='index'),
]

perfis/views.py:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return render(request, "index.html")

Maiores explicações sobre as mudanças podem ser encontradas aqui: https://stackoverflow.com/questions/38744285/django-urls-error-view-must-be-a-callable-or-a-list-tuple-in-the-case-of-includ