Problem with django-RESTframework-Tutorial - django

I'm trying to get familiar with django-RESTframeworks, therefore I started the official tutorial, to create a Test-API.
https://www.django-rest-framework.org/tutorial/quickstart/#quickstart
When finally starting the API on my Windows via [CMD] "pyhon manage.py runserver", I get an error code on the command line, which you will see below.
I also want to add, that unfortunately, there is some ambiguity in the descriptions in the tutorial, at least from the viewpoint of a beginner, i.e. it's not always certain whether the corresponding code in the tutorial
needs to be added in a module or replace all or part of the code in the modules.
Therefore, I tried implementing the directions of the tutorial in various ways, always with the same end result.
I'm running the code in a virtual env, where i've installed Django 1.11., so there shouldn't be an issue with different Django versions.
C:\Users\Rolimar\projects\djREST_tut>workon djresttut
(djresttut) C:\Users\Rolimar\projects\djREST_tut>python manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x0000000004CBF978>
Traceback (most recent call last):
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\urls\resolvers.py", line 256, in check
for pattern in self.url_patterns:
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module
return import_module(self.urlconf_name)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\Rolima\projects\djREST_tut\tutorial\urls.py", line 19, in <module>
from django.urls import include, path
ImportError: cannot import name include
And here my codes, I tried to copy from the tutorial:
"serializers.py"
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')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
"views.py"
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
"urls.py"
"""tutorial 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
from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
in "settings.py", where I added 'rest_framework'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
'rest_framework',
]
and where I also added the following code in the very end:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}

Most probably you are using django<2.0 but following tutorials which are written in django>2.0. From django 2.0, include has been moved to django.urls, before it resided in django.conf.urls(changelog reference). So you need to update your urls.py like this:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can't use path as well, because it was introduced in django 2 as well.
Or you can move to django>2.0, but in that case you have to remove from django.conf.urls import url and use from django.urls import url.

Related

ModuleNotFoundError: No module named 'router'

Hi i am getting this error please help me.
i am new on this field and i am getting this error.
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'first',
]
my views.py
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .serializers import MovieSerializer,RatingSerializers
from .models import Movie,Rating
# Create your views here.
class MovieViewSet(ModelViewSet):
queryset=Movie.objects.all()
serializer_class=(MovieSerializer,)
class RatingViewSet(ModelViewSet):
queryset=Rating.objects.all()
serializer_class=(RatingSerializers,)
my main urls.py is
"""rest_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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 path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('my_apis',include('first.urls')),
]
and serializers.py
from rest_framework import serializers
from .models import Movie,Rating
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model= Movie
fields=['title','description']
class RatingSerializers(serializers.ModelSerializer):
class meta:
model=Rating
fields='__all__'
models.py is
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator,MaxValueValidator
# Create your models here.
class Movie(models.Model):
title=models.CharField(max_length=20)
description =models.TextField(max_length=500)
def __str__(self):
return self.title
class Rating(models.Model):
movie=models.ForeignKey(Movie,on_delete=models.CASCADE)
user=models.ForeignKey(User,on_delete=models.CASCADE)
rating=models.PositiveIntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
class Meta:
unique_together=(('user','movie'))
index_together=(('user','movie'))
my urls.py (application)
from django.urls import path
from django.conf.urls import include
from rest_framework import routers
from .views import ModelViewSet,RatingViewSet
router=routers.DefaultRouter()
router.register('movies',ModelViewSet,basename='Movie')
router.register('rating',RatingViewSet,basename='Rating')
app_name='first'
urlpatterns = [
path('',include('router.urls')),
]
i am following a video tutorial
and getting that error
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'router'
please help me
ignore that this text is to avoid "it's look like post is mostly code,please add something "
urlpatterns = [
path('',include('router.urls')),
]
should be:
urlpatterns = router.urls
The include expression goes looking for a router module.
Use
path('', include(router.urls))
without quotes

can't use reverse url function in django

tests.py
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from .models import User
class UserCreateAPIViewTestCase(APITestCase):
def setUp(self):
super().setUp()
self.url = reverse("admins")
def test_user_creating(self):
user_data = {}
response = self.client.post(self.url, user_data, format="json")
self.assertEqual(response.status_code,
status.HTTP_403_FORBIDDEN)
2.urls.py
from django.urls import path
from django.conf.urls import include
from rest_framework_nested.routers import SimpleRouter
from apps.users.views import (
CreateProviderViewSet,
LoginViewSet,
UserViewSet,
ProviderViewSet,
ClientViewSet,
LoginAsViewSet
)
app_name = 'users'
router = SimpleRouter(trailing_slash=False)
router.register("admins", UserViewSet, base_name='admins')
router.register("providers", ProviderViewSet, base_name='providers')
router.register("clients", ClientViewSet, base_name='clients')
router.register("login", LoginViewSet, base_name='auth')
router.register("login-as", LoginAsViewSet)
urlpatterns = [
path('', include(router.urls)),
]
when I run python .\manage.py test apps.users.tests
This error occurs
ERROR: test_user_creating (apps.users.tests.UserCreateAPIViewTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\vu.tran\Desktop\kona-server\apps\users\tests.py", line 19, in setUp
self.url = reverse("admins")
File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\base.py", line 90, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\resolvers.py", line 668, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'admins' not found. 'admins' is not a valid view function or pattern name.
my structure folders like this my folders
I wonder why cannot get reverse("admins")
Do you have any idea?
According to the documentation, if you want to access the list view, the name for the url should be admins-list. The name of the argument for your register function may also be basename instead of base_name.

when i startapp "article", and python manage.py runserver, and I do not know why "module 'article.admin' has no attribute 'site" this error happen?

I start up an app named "article" but and configure an import like this: from article import * in the setting configure file, then when I run python manage.py runserver the error ocuur like this AttributeError: module 'article.admin' has no attribute 'site', when I comments from article import * with #, it will work on well, I do not know how from article import * raise the problem.
from article import *
atterns = [
path('admin/', admin.site.urls),
url(r'^article/',include('article.urls',namespace='article')),
]
The output:
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "D:\pythonTestfolder\xuegod\blogtest\blogtest\urls.py", line 25, in <module>
path('admin/', admin.site.urls),
AttributeError: module 'article.admin' has no attribute 'site'
You don't need to import from your article app here
especially all of its contents with *
include method will work with a string of app_name and it's urls.py file , as you have wright corectly
and after that if it is a newer version of django project you are using , try not to use
url method because it is going to be deprecated use re_path() instead , if you want to check for regex urls:
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^article/',include('article.urls',namespace='article')),
]

Error Specifying a namespace in include() without providing an app_name

When I tried my project runserver, this error
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\apple\Desktop\web3start\tests\urls.py", line 8, in <module>
url(r'^', include('web3auth.urls', namespace='web3auth')),
File "C:\Users\apple\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 39, in include
'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in
the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
came out.
conf.py
if isinstance(urlconf_module, str):
urlconf_module = import_module(urlconf_module)
patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
app_name = getattr(urlconf_module, 'app_name', app_name)
if namespace and not app_name:
raise ImproperlyConfigured(
'Specifying a namespace in include() without providing an app_name '
'is not supported. Set the app_name attribute in the included '
'module, or pass a 2-tuple containing the list of patterns and '
'app_name instead.',
urls.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('web3auth.urls', namespace='web3auth')),
]
What should I do?? I need a specific code directly to write on!
As the error said, inside your web3auth/urls.py you need to set app_name attribute. For example:
# web3auth/urls.py
from django.urls import path
from . import views
app_name = 'web3auth'
urlpatterns = [
...
]
You can checkout the documentation as well.

"Posts matching query does not exist." error while navigating to "admin page" in django?

I am learning Django and working on making a simple blog website. Now the whole project is working fine but whenever I navigate to the admin panel it shows the error "Posts matching query does not exist.".
Let me know which part of the code you want to see(i'm confused which file has the error)
error :
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Django Version: 2.0.5
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e,
request)
File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "C:\Users\Fruity_Dude\Projects\Django\devflow\posts\views.py" in
post_details
10. posts = Posts.objects.get(slug=slug)
File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args,
**kwargs)
File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site-
packages\django\db\models\query.py" in get
403. self.model._meta.object_name
Exception Type: DoesNotExist at /admin
Exception Value: Posts matching query does not exist.
urls.py:
from django.urls import path
from . import views
app_name = 'posts'
urlpatterns = [
path('', views.posts, name='home'),
path('<slug:slug>', views.post_details, name='detail'),
]
views.py:
from django.shortcuts import render
from .models import Posts
from django.http import HttpResponse
def posts(request):
posts = Posts.objects.all().order_by('date')
return render(request, 'posts/posts.html', {'posts': posts})
def post_details(request, slug):
posts = Posts.objects.get(slug=slug)
return render(request, 'posts/post_details.html', {'posts': posts})
main urls.py:
from django.contrib import admin
from django.urls import path,include
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls), #for admin
path('', include('posts.urls')),
path('about/', views.about, name='about'), #for about
path('contact/', views.contact, name='contact'), #for contact
path('support/', views.support, name='support'), #for support
path('donate/', views.donate, name='donate') #for donate
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The problem seem to be that you are running
posts = Posts.objects.get(slug=slug)
and your url catches
path('<slug:slug>', views.post_details, name='detail')
For instance when you do http://domain:port/a-post/ what will be matched in argument slug is 'a-post/' (notice the trailing /)
You wrote in a comment that
url(r'^(?P<slug>[\w-]+)/$', views.post_details, name='detail')
fixed the issue. That is probably because the trailing / is now not included in the resulting slug variable.
The error is raised by Posts.objects.get(slug=slug) since the .get-method requires one and only one row to be matched. (see django docs)
To avoid that problem, I see two solutions you should implement.
Change the match to path('<slug:slug>/', views.post_details, name='detail'), i.e. added a /.
Use the filter-method.
For example:
posts = Posts.objects.filter(slug=slug).all() # all() to make django perform the sql select command and return list
if not posts:
# handle error case, either return 404 or redirect somewhere.
elif len(posts) > 1:
# handle the weird case when there was more than one matching post
post = posts[0]
# render using post instead of posts, since it is only one post