Circular import error when I open the Django server - python

When I open the server(Django) I get this error: "The included URLconf 'admin.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."
I have found out that by removing .views import from urls.py I fix the issue. So I think the problem is inside views.py.
App urls.py
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('/api', include('crud.urls')),
]
views.py
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from .serializers import UserSerializer
class UserView(APIView):
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response({"users": users})
serializer.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255)
email = serializers.EmailField()
password = serializers.CharField(max_length=255)
disease = serializers.CharField(max_length=255)
logo = serializers.TextField()
crud urls.py
Here, the issue is at the second line: if I remove that line I fix the error
from django.urls import path
from .views import UserView
app_name='crud'
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('users/', UserView.as_view()),
]

Please add error trace for better understanding of the issue.
Meanwhile try changing this:
path('/api', include('crud.urls'))
to:
path('api/', include('crud.urls')),
and
from .views import UserView
to:
from crud import views
urlpatterns = [
path('users/', views.UserView.as_view()),
]

Related

Attribute Error while importing views in Urls.py in django rest framework

views.py
from rest_framework.decorators import api_view
from rest_framework import status
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from App.serializers import *
from App.models import *
from App.serializers import *
# Create your views here.
class ListUsers(APIView):
"""
View to list all users in the system.
* Requires token authentication.
* Only admin users are able to access this view.
"""
authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAdminUser]
def get(self, request, format=None):
"""
Return a list of all users.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email
})
#api_view(['GET'])
def consol_overall_view(request):
user = Users.objects.values('id','employee_name','billable_and_non_billable',)
qs = conso_serializers(user, many= True)
proj = Add_Job.objects.values('project','user','client')
qs1 = timelog_serializers(proj, many= True)
cli = Add_Timelog.objects.values('Date','Hours','project_id')
qs2 = time_serializers(cli,many= True)
return Response(qs.data+qs1.data+qs2.data,status = status.HTTP_200_OK)
urls.py
from django.contrib import admin
from django.urls import path,include
from django.urls import re_path
from django import views
from App.views import CustomAuthToken
from.router import router
from rest_framework.authtoken import views
from django.views.generic import TemplateView
from App.views import consol_overall_view
urlpatterns = [
path('', TemplateView.as_view(template_name="social_app/index.html")),
path('admin/', admin.site.urls),
path('api/',include(router.urls)),
path('accounts/', include('allauth.urls')),
re_path('rest-auth/', include('rest_auth.urls')),
path('api-auth/', include('rest_framework.urls')),
re_path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('api-token-auth/', views.obtain_auth_token),
path('api-token-auth/', CustomAuthToken.as_view()),
path('over',views.consol_overall_view),
]
while I tried to migrate and runserver it is showing an error
path('over',views.consol_overall_view),
AttributeError: module 'rest_framework.authtoken.views' has no attribute 'consol_overall_view'
I need the consol_overall_view in Url or as a API. If it is possible to do as API kindly guide on the same.
When python interpreter finds imports with same name it takes the latest one into account. In your urls.py you have imported views module from two distinct packages. Python interpreter will treat the name views from the package restframework.authtoken as the views module not the one from django because the import from the first one is the latest. Apart from that, you have imported consol_overall_view directly from App.views but referring it as a value from views that you have imported before. Change views.consol_overall_view to consol_overall_view in your urlpatterns. Also, use aliases in your imports.
from django.contrib import admin
from django.urls import path,include
from django.urls import re_path
# import django.views with alias
from django import views as django_views
from App.views import CustomAuthToken
from.router import router
from rest_framework.authtoken import views
from django.views.generic import TemplateView
from App.views import consol_overall_view
urlpatterns = [
path('', TemplateView.as_view(template_name="social_app/index.html")),
path('admin/', admin.site.urls),
path('api/',include(router.urls)),
path('accounts/', include('allauth.urls')),
re_path('rest-auth/', include('rest_auth.urls')),
path('api-auth/', include('rest_framework.urls')),
re_path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('api-token-auth/', views.obtain_auth_token),
path('api-token-auth/', CustomAuthToken.as_view()),
path('over', consol_overall_view),
]

Django error 404 2458 when requesting objects by id

I am following this video trying to learn Django. I have completed this tutorial and I had the same problem even when I followed the code to a T.
I am trying to get information about a model object displayed on the web-page when entering the id of the object directly in the url like http://localhost:8000/app/item/1/ or http://localhost:8000/app/item/2/ as the video shows (7:30 into the video). But when I try, I get this error:
Original code from video:
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Book
def index(request):
return HttpResponse('Hello, world!')
def book_by_id(request, book_id):
book = Book.objects.get(pk=book_id)
return HttpResponse(f"Book: {book.title}, published on {book.pub_date}")
models.py:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
urls.py:
from django.utils import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('book/<int:book_id>', views.book_by_id, name='book_by_id'),
]
My code:
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Item
def index(request):
return HttpResponse('Hello, world!')
def item_by_id(request, item_id):
item = Item.objects.get(pk=item_id)
return HttpResponse(f"Item: {item.title}, published on {item.datetime_found}")
models.py:
from django.db import models
from django.utils.timezone import now
class Item(models.Model):
title = models.CharField(max_length=200) # Short description of the item
datetime_found = models.DateTimeField(default=now, blank=True) # Date and time of when the item was found
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('item/<int:item_id>', views.item_by_id, name='item_by_id'),
]
Project-level urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('myapp.urls')),
path('admin/', admin.site.urls),
]
What am I not getting right about the GET-request? I feel like the changes I've made are minimal. And I have migrated everything correctly. (I think)
Use this
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('app/', include('myapp.urls')),
path('admin/', admin.site.urls),
]
or you can remove 'app' from your url and make it look like this http://127.0.0.1:8000/item/1
look at url pattern of yours and the original.
path('item/<int:item_id>', views.item_by_id, name='item_by_id'),
is yours
path('book/<int:book_id>', views.book_by_id, name='book_by_id'),
is the original

Rest API . Help to change ListView

I have some error with Rest API when started Django project.
The error is
"raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'api.urls' from '/Users/luba/code/library/library_project/api/urls.py'>' 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."
My code:
api/views.py
from rest_framework import generics
from books.models import Book
from .serializers import BookSerializer
class BookAPIView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
api/urls.py
from django.urls import path
from .views import BookAPIView
urlpattens = [
path('', BookAPIView.as_view()),
]
api/serializers.py
from rest_framework import serializers
from books.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'subtitle', 'author', 'isbn')
books/views.py
from django.urls import path
from .views import BookListView
urlpatterns = [
path('', BookListView.as_view(), name='home'),
]
books/views.py
from django.views.generic import ListView
from .models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'
Somebody can explain, in which staff problem with my code.Will be appreciate!!!!
It seems like you didn't include your api urls to main urls.py
You can find it at same folder where your settings.py is located.
from django.urls import path, include
from api import urls
urlpatterns = [
path('api/', include(urls.urlpatterns)),
]

OperationalError at /admin/todo/todo/ in Django

I'm making a basic Todo app in Django.
While going to the admin page and clicking on the Todo option:
It gives me this error:
The "todo" string appears twice in the URL.
I have already done the migrations thing and I have added the todo.apps.TodoConfig in the INSTALLED_APPS.
Here is my code:
todo app urls.py
from django.urls import path
from todo import views
urlpatterns = [
path('', views.index),
path('todo/', views.index,)
]`
todo app views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello ")
todo app models.py
from django.db import models
from datetime import datetime
class Todo(models.Model):
title = models.CharField(max_length = 200)
text = models.TextField()
created_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.title
todo app admin.py
from django.contrib import admin
from .models import Todo
admin.site.register(Todo)
The main project urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('ToDoList/', include('ToDoList.urls')),
path('Todo/', include('todo.urls')),
]
try saving the admin.py file
maybe in admin.py add this code:
from django.contrib import admin
from .models import Todo
admin.site.register(Todo)
Check It And Go!!!

error with serialization in django rest framework

I use django rest framework and have this error:
base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .model or .queryset attribute.
This is my code
urls.py
from django.conf.urls import patterns, include, url
from rest_framework import viewsets, routers
import views
router = routers.SimpleRouter()
router.register(r'book', views.BookViewSet.as_view())
views.py
from django.shortcuts import render_to_response
from mobileapp.models import Book
from rest_framework import generics
from mobileapp.serializers import BookSerializer
class BookViewSet(generics.ListAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
serializers.py
from mobileapp.models import Book
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'url', 'date', 'comment')
Have you google'd error statement?
https://github.com/tomchristie/django-rest-framework/issues/933
http://django-rest-framework.org/api-guide/routers.html#usage
I'v solved my problem. There is code.
urls.py
from django.conf.urls import patterns, include, url
from views import BookList, BookDetail
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^book/$', BookList.as_view(), name='book-list'),
url(r'^book/(?P<pk>\d+)/$', BookDetail.as_view(), name='book-detail'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
views.py
class BookList(generics.ListCreateAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
model = Book
serializer_class = BookSerializer

Categories

Resources