how to fix circular import in django? - python

I'm trying to create an api that uploads an image with an email to the database. But I'm getting an error "raise ImproperlyConfigured(msg.format(name=self.urlconf_name))" Is the problem in my urls.py?
https://imgur.com/OjPUhOv.jpg
This is how my structure looks
https://imgur.com/TW6pKPn.jpg
This is the error
for urls.py-
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('user.urls')),
path('api/',include('api_test.urls'))
# path('articles/',include('articles.urls'))
]
for api_test/urls.py
from django.urls import path,include
from django.conf import settings
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('image_test',views.api_test,base_name='image_test')
urlpatterns = [
# path('/',views.api_test),
path('',include(routers.url)),
]
for views.py
class api_test(viewsets.ModelViewSet):
queryset = fineDB.objects.all()
serializer_class = fineSerializer
##for serializers.py
from rest_framework import serializers
from .models import fineDB
class fineSerializer(serializers.ModelSerializer):
image = serializers.ImageField(max_length=None,use_url=True)
class Meta:
model = fineDB
fields = {'email','image'}

You should probably get the urls from router, not routers.
At the same time you don't need both the router and the urlpatterns in that file. You can import the router and mount it's router.urls in urls.py.
from rest_framework import routers
router = routers.DefaultRouter()
router.register('image_test',views.api_test,base_name='image_test')
urlpatterns = [
# path('/',views.api_test),
path('',include(router.urls)), # <-
]

Related

Python ModuleNotFoundError: I can't import my module

I have got a CRUD App, I'm learning API rest with Python and Django... I create this module:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model: User
fields = ['url', 'username', 'email', 'groups']
And after that, I write this:
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from djangoCRUD.Api.serializer import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().orderby('-date_joined')
serializer_class = UserSerializer
This is all right, but, when I write my url.py Here, I have got a problem:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from djangoCRUD.Api import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
And I have this error message:
File "C:\PythonDev\pythoncrud\venv\djangoCRUD\djangoCRUD\urls.py", line 20, in
from djangoCRUD.Api import views
ModuleNotFoundError: No module named 'djangoCRUD.Api'
Try the following code:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
# from djangoCRUD.Api import views
from djangoCRUD.Api.views import UserViewSet
router = routers.DefaultRouter()
# router.register(r'users', views.UserViewSet)
router.register(r'users', UserViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

django ImpropertlyConfigured. The included urlsconf does not appear to have any patterns in it

I am using django 2.2.2 . I am trying to include path('api/', include('music.urls')),into my root url but I get an exception thrown from resolvers.py file.
Here is my music/urls.py
urls.py
from django.urls import path
from . import views
app_name = 'music'
urlpatterns = [
path('songs/', ListSongsView.as_view(), name = 'songs-all'),
]
here is my root url file
urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('music.urls')),
]
views.py
from django.shortcuts import render
from rest_framework import generics
from .models import Songs
from serializers import SongSerializer
# Create your views here.
class ListSongsView(generics.ListApiView):
queryset = Songs.objects.all()
serializer_class = SongsSerializer
models.py
from django.db import models
# Create your models here.
class Songs(models.Model):
title = models.CharField(max_length=255, null = False)
artist = models.CharField(max_length=50, null= False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
and my stacktrace
File "/home/brianonchari/Documents/django/drf/myapi/lib/python3.5/site-
packages/django/urls/resolvers.py", line 588, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'rest.urls' does not
appear to have any patterns in it. If you see valid patterns in the file then the issue is
probably caused by a circular import.
music/urls.py
from django.urls import path
from .views import ListSongsView
app_name = 'music'
urlpatterns = [
path('songs/', ListSongsView.as_view(), name='songs-all'),
]
root urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('music.urls')),
]
music/views.py:
from django.shortcuts import render
from rest_framework import generics
from .models import Songs
from .serializers import SongSerializer
# Create your views here.
class ListSongsView(generics.ListAPIView):
queryset = Songs.objects.all()
serializer_class = SongSerializer
music/models.py:
from django.db import models
# Create your models here.
class Songs(models.Model):
title = models.CharField(max_length=255, null=False)
artist = models.CharField(max_length=50, null=False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
music/serializers.py:
from rest_framework import serializers
from .models import Songs
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Songs
fields = ('title', 'artist')
run your migration for Songs model:
python manage.py makemigrations
python manage.py migrate

Trying to trace a circular import error in Django Python

I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'

ValueError: too many values to unpack (expected 3) in url config

I have a django project with django-rest-framework named MyProject in which I have created an app accounts.
I have the following code inside MyProject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('accounts.urls', namespace='accounts')),
path('admin/', admin.site.urls),
]
Inside MyProject/accounts/urls.py, I have:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('accounts', views.UserView)
urlpatterns = [
path('', router.urls)
]
Inside MyProject/accounts/views.py:
import sys
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
from rest_framework import viewsets
from .serializers import UserSerializer
class UserView(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
I am getting the error:
> File
> "C:\Users\user\PycharmProjects\MyProject\accounts\urls.py",
> line 10, in <module>
> path('', router.urls) File "C:\Users\user\PycharmProjects\MyProject\venv\lib\site-packages\django\urls\conf.py",
> line 61, in _path
> urlconf_module, app_name, namespace = view ValueError: too many values to unpack (expected 3)
The router.urls contains a list of urls. You can simply set the urlpatterns to that list:
router = routers.DefaultRouter()
router.register('accounts', views.UserView)
urlpatterns = router.urls
Or you can append the values if you want to make other paths:
router = routers.DefaultRouter()
router.register('accounts', views.UserView)
urlpatterns = [
# …
]
urlpatterns += router.urls

Custom templates for custom AdminSite Django

I have two admin sites and I want to have different custom templates on both of them
This is my admin.py file:
from django.contrib import admin
from django.contrib.admin import AdminSite
from .models import Equipo
#admin.register(Equipo)
class EquipoAdmin(admin.ModelAdmin):
list_display = ('codigo', 'nombre', 'contador', 'unidades')
class AdminMantenimiento(AdminSite):
site_header = "MANTENIMIENTO"
class EquipoAdminMantenimiento(admin.ModelAdmin):
list_display = ('codigo', 'nombre')
admin_site = AdminMantenimiento(name='Administrador Mantenimiento')
admin_site.register(Equipo, EquipoAdminMantenimiento)
This is my urls.py file:
from django.contrib import admin
from django.urls import path
from Mantenimiento.admin import admin_site
urlpatterns = [
path('admin/', admin.site.urls),
path('admin2/',admin_site.urls)
]
If I override the templates as per Django documentation changes would be applied to both AdminSites. How can I set custom templates for the class extending AdminSite?
The only way I could think to do this would be to explicitly override the url of the admin page you want to customize and point it to a different template. For example to customize a template in admin2/ but not admin1/
from django.contrib import admin
from django.urls import path
from Mantenimiento.admin import admin_site
from app.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('admin2/app/model', TemplateView.as_view(template_name='model_admin.html')),
path('admin2/', admin_site.urls)
]
This will only work if the more specific url definition (admin2/app/model) comes before the less specific definition (admin2/)

Categories