Python ModuleNotFoundError: I can't import my module - python

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'))
]

Related

SimpleJwtAuthentication problem ...Even after presence of user ,url not giving token

i am using this model extending from abstractuser but even after successfully creating user i am not able to get the tokens....
Tokens are genrerated only for those which i created through python manage.py createsuperuser ..others not working.
why????
i am using simplejwt authentication.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class user_model(AbstractUser):
email=models.CharField(max_length=200,blank=True)
age=models.CharField(max_length=200,blank=True)
dob=models.CharField(max_length=200,blank=True)
phone=models.CharField(max_length=200,blank=True)
def __str__(self):
return self.username
urls.py
from django.contrib import admin
from django.urls import path,include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('signup/',include('userdata.urls')),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('loggedIn/',include("notes.urls")),
]

TypeError at /api/questions/ 'list' object is not callable

When I go to this http://127.0.0.1:8000/api/questions/ I get
TypeError at /api/questions/
'list' object is not callable
urls.py
(in project)
"""QuestionTime URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path, re_path
from django_registration.backends.one_step.views import RegistrationView
from core.views import IndexTemplateView
from users.forms import CustomUserForm
# https://django-registration.readthedocs.io/en/3.1.2/activation-workflow.html
urlpatterns = [
path('admin/', admin.site.urls),
path("accounts/register/", RegistrationView.as_view(
form_class=CustomUserForm,
success_url="/",
), name="django_registration_register"),
path("accounts/", include("django_registration.backends.one_step.urls")),
path("accounts/", include("django.contrib.auth.urls")),
path("api/", include("users.api.urls")),
path("api/", include("questions.api.urls")),
path("api-auth/", include("rest_framework.urls")),
path("api/rest-auth/", include("rest_auth.urls")),
path("api/rest-auth/registration/", include("rest_auth.registration.urls")),
re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point"),
]
urls.py
(in appName1/api
from django.urls import include, path
from rest_framework import urlpatterns
from rest_framework.routers import DefaultRouter
from questions.api import views as qv
router = DefaultRouter()
router.register(r"questions", qv.QuestionViewSet)
urlpatterns = [
path("", include(router.urls)),
path("questions/<slug:slug>/answers/", qv.AnswerListAPIView.as_view(), name="answer-list"),
path("questions/<slug:slug>/answer/", qv.AnswerCreateAPIView.as_view(), name="answer-create"),
path("answers/<int:pk>/", qv.AnswerRUDAPIView.as_view(), name="answer-detail"),
path("answers/<int:pk>/like/", qv.AnswerLikeAPIView.as_view(), name="answer-like"),
]
views.py
(in appName1/api)
Only showing QuestionViewSet
class QuestionViewSet(viewsets.ModelViewSet):
queryset = Question.objects.all()
lookup_field = "slug"
serializer_class = QuestionSerializer
permission_classes = [IsAuthenticated, IsAuthorOrReadOnly]
def perform_create(self, serializer):
serializer.save(author=self.request.user)
From the settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_PAGINATION_CLASS': (
'rest_framework.pagination.PageNumberPagination',
),
'PAGE_SIZE': 2,
}
Error could come from somewhere else.
I don't know where I can find "list".
appName1 = questions
Exception Location: lib/python3.9/site-packages/rest_framework/generics.py, line 162, in paginator
The DEFAULT_PAGINATION_CLASS setting should be a string not a tuple/list
REST_FRAMEWORK = {
...
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
...
}

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

how to fix circular import in django?

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)), # <-
]

Categories