4
respostas

Erro em configurando Urls

Até a aula anterior o código estava rodando lindamente, consegui adicionar alunos e cursos pelo admin no navegador. Depois dessa aula, começou a aparecer esse erro.

Uso essa importação from RestAPI.escola.models import Aluno, Curso mas porque se eu não usasse a pasta RestAPI (onde esta a escola) dava ruim. Alguém pode me ajudar, por favor?

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/lorraine/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/home/lorraine/anaconda3/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate
    app_config.ready()
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 27, in ready
    self.module.autodiscover()
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "/home/lorraine/Documentos/Mentoria/RestAPI/venv/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "/home/lorraine/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/lorraine/Documentos/Mentoria/RestAPI/escola/admin.py", line 2, in <module>
    from RestAPI.escola.models import Aluno, Curso
ModuleNotFoundError: No module named 'RestAPI'

4 respostas

Segue o código

MODELS

from django.db import models

# Create your models here.
class Aluno(models.Model):
    nome = models.CharField(max_length=30)
    rg = models.CharField(max_length=9)
    cpf = models.CharField(max_length=11)
    data_nascimento = models.DateField()

    def __str__(self):
        return self.nome

class Curso(models.Model):
    NIVEL = (
        ('B', 'Basico'),
        ('I', 'Intermediário'),
        ('A', 'Avançado')
    )

    codigo_curso = models.CharField(max_length=10)
    descricao = models.CharField(max_length=100)
    nivel = models.CharField(max_length=1, choices=NIVEL, blank=False, null=False, default='B')

    def __str__(self):
        return self.descricao

SERIALIZER

from rest_framework import serializers
from RestAPI.escola.models import Aluno, Curso

#Filtro dos dados que eu quero na api

class AlunoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Aluno
        fields = ['id', 'nome', 'rg', 'cpf', 'data_nascimento']

class CursoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Curso
        fields = '__all__'

URLS

from django.contrib import admin
from django.urls import path, include
from RestAPI.escola.views import AlunosViewSet, CursosViewSet
from rest_framework import routers #rota para navegar

router = routers.DefaultRouter() #rota principal criada
router.register('alunos', AlunosViewSet, basename='Alunos')
router.register('cursos', CursosViewSet, basename='Cursos')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(router.urls)),
]

ADMIN

from django.contrib import admin
from RestAPI.escola.models import Aluno, Curso

class Alunos(admin.ModelAdmin):
    list_display = ('id', 'nome', 'rg', 'cpf', 'data_nascimento')
    list_display_links = ('id', 'nome') #possivel de aterar
    search_fields = ('nome',) #campo de busca
    list_per_page = 20 #20 alunos por pagina

admin.site.register(Aluno, Alunos) #registrando aluno

class Cursos(admin.ModelAdmin):
    list_display = ('id', 'codigo_curso', 'descricao')
    list_display_links = ('id', 'codigo_curso')
    search_fields = ('codigo_curso',)

admin.site.register(Curso, Cursos)#registrando cursos

VIEWS

from rest_framework import viewsets
from RestAPI.escola.models import Aluno, Curso
from serializer import AlunoSerializer, CursoSerializer

class AlunosViewSet(viewsets.ModelViewSet):
    """Exibindo todos os alunos e alunas..."""
    queryset = Aluno.objects.all()#posso filtrar se quiser
    serializer_class = AlunoSerializer

class CursosViewSet(viewsets.ModelViewSet):
    """Exibindo todos os cursos"""

    queryset = Curso.objects.all()
    serializer_class = CursoSerializer
O post foi fechado por inatividade. Para continuar o assunto, recomendamos criar um novo tópico. Bons Estudos!