Iam trying to implement django rest framework. I am having this error:
File "F:\....\urls.py", line 19, in <module>
from Userinfo import views
File "F:\....\Userinfo\views.py", line 8, in <module>
from .serializers import usersSerializer
File "F:\.....\Userinfo\serializers.py", line 2, in <module>
from rest_framework import users
ImportError: cannot import name 'users' from 'rest_framework' (C:\Users\....\rest_framework\__init__.py)
My urls.py code:
from django.contrib import admin
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
from Userinfo import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('UserData', views.UserList.as_view()),
]*
my views.py code:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import users
from .serializers import usersSerializer
class UserList(APIView):
def get(self, request):
user1 = users.objects.all()
serializer = usersSerializer(user1, many = True)
return Response(serializer.data)*
my serializers.py code:
from rest_framework import serializers
from rest_framework import users
class usersSerializer(Serializers.ModelSerializer):
class Meta:
model = users
fields = '__all__'*
my models.py code:
from django.db import models
class users(models.Model):
Name = models.CharField(max_length=50)
id = models.IntegerField(primary_key=True)
DocumentCount = models.IntegerField()
Role = models.CharField(max_length=15)
def _str_(self):
return self.name + self.id*
The code might be incomplete but I'll provide as much information as possible.
In your serializers.py:
from rest_framework import serializers
# from rest_framework import users # remove this
from django.contrib.auth import get_user_model # add this
User = get_user_model()
class usersSerializer(Serializers.ModelSerializer):
class Meta:
model = Users
# model = get_user_model() # this will work too
fields = '__all__'
Related
I have a class-based view that returns all the data in the table. But while accessing the URL all I get is an empty list.
models.py
from django.db import models
class EmployeeModel(models.Model):
EmpID = models.IntegerField(primary_key=True)
EmpName = models.CharField(max_length=100)
Email = models.CharField(max_length=100)
Salary = models.FloatField()
class Meta:
verbose_name = 'employeetable'
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import EmployeeModel
from .serializers import EmployeeSerialize
class EmployeeTable(APIView):
def get(self,request):
emp_obj = EmployeeModel.objects.all()
empserializer = EmployeeSerialize(emp_obj,many=True)
return Response(empserializer.data)
serializers.py
from rest_framework import serializers
from .models import EmployeeModel
class EmployeeSerialize(serializers.ModelSerializer):
class Meta:
model = EmployeeModel
fields = '__all__'
urls.py
from django.contrib import admin
from django.urls import path, include
from .views import EmployeeTable, transformer_list
urlpatterns = [
path('display/',EmployeeTable.as_view()),
]
The table has 5 rows. It is not empty.
I want to serialize all 5 rows
I have also created the same but in my case, it worked see the below images
See my serializer
See my models below
and my output is here below
I think there are some issue at your code or some mistake can be there can you please provide full information
ImproperlyConfigured at /snippet/5
Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
models.py
from email.policy import default
import imp
from tkinter import CASCADE
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
from django.contrib.auth.models import User
import snippets
# Create your models here.
LEXERS=[item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES=sorted([(item[1][0],item[0]) for item in LEXERS])
STYLE_CHOICES=sorted([(item,item)for item in get_all_styles()])
class Snippet(models.Model):
created=models.DateTimeField(auto_now_add=True)
title=models.CharField(max_length=100,blank=True,default='')
code=models.CharField(max_length=250,default="0")
linenos=models.BooleanField(default=False)
language=models.CharField(choices=LANGUAGE_CHOICES,default='python',max_length=100)
style=models.CharField(choices=STYLE_CHOICES,default='friendly',max_length=100)
owner=models.ForeignKey('auth.User',related_name='snippets',on_delete=models.CASCADE)
class Meta:
ordering=['created']
permissions.py
import imp
from rest_framework import permissions
class IsOwnerReadOnly(permissions.BasePermission):
"""custom permissions to only allow owners of an oject to edit
"""
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user
serializers.py
from operator import mod
from numpy import source
from .models import *
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES,STYLE_CHOICES
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model=Snippet
fields = ['url', 'id', 'owner',
'created', 'title', 'linenos', 'language', 'style']
# fields='__all__'
# fields=['id','url','owner']
from django.contrib.auth.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets=serializers.HyperlinkedRelatedField(lookup_field = 'username',many=True,view_name='snippet-details',read_only=True)
owner=serializers.ReadOnlyField(source='owner.username')
class Meta:
model= User
fields=['id','username','snippets','owner']
views.py
from snippets.models import Snippet
from snippets.permissions import IsOwnerReadOnly
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from snippets.permissions import IsOwnerReadOnly
from rest_framework import permissions
class snippet_list(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class snippet_detail(generics.RetrieveUpdateDestroyAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly,IsOwnerReadOnly]
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
########################## authentication purspose #####################################################
from django.contrib.auth.models import User
from .serializers import *
from rest_framework import permissions
class UserList(generics.ListAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly]
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly]
queryset = User.objects.all()
serializer_class = UserSerializer
####################################### using hyperlinking for relationships #################################################################
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
#api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
urls.py(api)
from rest_framework.urlpatterns import format_suffix_patterns
from django.urls import path,include
from snippets import views
from .views import *
urlpatterns=format_suffix_patterns([path('',views.api_root),
path('snippet/',views.snippet_list.as_view(),name='snippet-list'),
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-details'),
path(' ',views.UserList.as_view(),name='user-list'),
path('Users/<int:pk>',views.UserDetail.as_view(),name='user-details'),
])
urls.py(main project)
from django.contrib import admin
# from snippets.urls import *
# from snippets.views import *
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('snippets.urls')),
]
########################## authentication purspose #####################################################
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]
I'm new for django but learning and implementing and also sorting errors. But I got stuck with this error for 2 days. I done many changes but still not working .
It appears to me that you misspelled the url name in the urls.py
You have
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-details'),
replace it with
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-detail')
remove the "s" from the name
I have a small web app, and I'm trying to develop an API for it. I'm having an issue with a model I have called Platform inside of an app I have called UserPlatforms. The same error: AttributeError: type object 'UserPlatformList' has no attribute 'get_extra_actions'
models.py:
class Platform(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='platform_owned',
on_delete=models.CASCADE,
default=10)
PLATFORM_CHOICES = [platform_x, platform_y]
platform_reference = models.CharField(max_length=10, choices=PLATFORM_CHOICES, default='platform_x')
platform_variables = models.JSONField()
api/views.py
from .serializers import PlatformSerializer
from rest_framework import generics, permissions
from userplatforms.models import Platform
class UserPlatformList(generics.ListCreateAPIViewAPIView):
queryset = Platform.objects.all()
permisson_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = PlatformSerializer
api/serializer.py
from rest_framework import serializers
from userplatforms.models import Platform
class PlatformSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Platform
fields = '__all__'
api/urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'userplatforms/', views.UserPlatformList, 'userplatforms')
router.register(r'userfiles/', views.UserFileList, "userfiles")
router.register(r'users/', views.UserList, "user")
urlpatterns = [
path("^", include(router.urls))
]
You cannot add generic Views in routers.
So remove this line:
router.register(r'userplatforms/', views.UserPlatformList, 'userplatforms')
and update urlpatterns to:
urlpatterns = [
path('userplatforms/', views.UserPlatformList, name='userplatforms'),
path("^", include(router.urls))
]
change class PlatformSerializer(serializers.HyperlinkedModelSerializer): to class PlatformSerializer(serializers.ModelSerializer):
api/views.py
from .serializers import PlatformSerializer
from rest_framework import generics, permissions
from userplatforms.models import Platform
class UserPlatformList(generics.ListCreateAPIViewAPIView):
queryset = Platform.objects.all()
permisson_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = PlatformSerializer
for the UserPlatformList inheritance, ListCreateAPIViewAPIView should be ListCreateAPIView
If you are using mixins to create the viewset, then it should be like
from .serializers import PlatformSerializer
from rest_framework import generics, permissions, viewsets
from userplatforms.models import Platform
class UserPlatformList(generics.ListModelMixin, viewsets.GenericViewSet):
queryset = Platform.objects.all()
permisson_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = PlatformSerializer
This way router can be used to set the urlpatterns
api/urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'userplatforms/', views.UserPlatformList, 'userplatforms')
router.register(r'userfiles/', views.UserFileList, "userfiles")
router.register(r'users/', views.UserList, "user")
urlpatterns = router.urls
I have to fetch the usernames of my authors' posts
Here the views.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .forms import CreateUserForm
from .models import Post
from .forms import PostForm
def counter(request):
authors = Post.objects.values_list('author', 'title')
authors_id = Post.objects.values_list('author')
authors_name = User.objects.get(id=authors_id)
context = {'authors':authors, 'authors_name':authors_name}
return render(request, 'account/counter.html', {'authors': authors})
My models.py is:
from django.db import models
from django.conf import settings
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
And here my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import Post
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined']
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'text', 'author']
Now the problem is that on 'authors_id' I have this Error: The QuerySet value for an exact lookup must be limited to one result using slicing, or if i get just one result value of the list the answer's error is: Field 'id' expected a number but got (3,).
So because it takes also the comma from 'values_list'.
I've to got back each author's post and the title of each post the author wrote.
How can I slice the queryset's list?
try this
authors_id = Post.objects.values_list('author', flat=True)
authors_name = User.objects.get(id__in=authors_id)
or
authors_id = Post.objects.values_list('author', flat=True)[0]
authors_name = User.objects.get(id=authors_id)
Refer this https://docs.djangoproject.com/en/3.1/topics/db/queries/#the-pk-lookup-shortcut
I'm making my first DRF api I get a strange AttributeError that I don't understand. When I try to access to my data using a GET request, I get this error:
Got AttributeError when attempting to get a value for field nom on
serializer ExpediteurSerializer. The serializer field might be named
incorrectly and not match any attribute or key on the type instance.
Original exception text was: type object 'QuerySet' has no attribute
'nom'.
I guess I've done something unexpected in my serializers.py file.. Here follows some snippets of my code.
models.py
from django.db import models
# Create your models here.
class Expediteur(models.Model):
nom = models.CharField(max_length=50)
prenom = models.CharField(max_length=100)
adresse = models.CharField(max_length=200)
tel = models.IntegerField()
views.py
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from polls.serializers import ExpediteurSerializer, DestinataireSerializer, LettrePrioSerializer, TypeLettreRecoSerializer, LettreRecoSerializer, TimbrePrioSerializer, TimbreRecoSerializer
from polls.models import Expediteur, Destinataire, LettrePrio, TypeLettreReco, LettreReco, TimbrePrio, TimbreReco
from rest_framework import status, HTTP_HEADER_ENCODING
from django.shortcuts import render, get_object_or_404
import json
import datetime
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth import login
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
from django.utils.timezone import get_current_timezone
# Create your views here.
class ExpeViewSet(APIView):
serializer_class = ExpediteurSerializer
def get(self, request):
queryset = Expediteur.objects.all()
serializer = ExpediteurSerializer(queryset)
return Response(serializer.data)
def post(self, request):
serializer = self.serializer_class(data=request.DATA)
return Response(status=status.HTTP_201_CREATED)
serializers.py
from rest_framework import serializers
from polls.models import Expediteur, Destinataire, LettrePrio, TypeLettreReco, LettreReco, TimbrePrio, TimbreReco
class ExpediteurSerializer(serializers.Serializer):
nom = serializers.CharField(required=True, allow_blank=False, max_length=50)
prenom = serializers.CharField(required=True, allow_blank=False, max_length=100)
adresse = serializers.CharField(required=True, allow_blank=False, max_length=200)
tel = serializers.IntegerField(required=True)
def create(self, validated_data):
return Expediteur.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.nom = validated_data.get('nom', instance.nom)
instance.prenom = validated_data.get('prenom', instance.prenom)
instance.adresse = validated_data.get('adresse', insatnce.adresse)
instance.tel = validated_data.get('tel', instance.tel)
instance.save()
return instance
I think you are missing the many flag in you view, like so:
ExpediteurSerializer(queryset, many=True)
In general you could simplify your code very much by fully utilizing DRF.
First, make ExpediteurSerializer a ModelSerializer according to the documentation.
Then you can also get rid of the create and update method, DRF takes care of all of that for you. And I strongly recommend you to look at ModelViewSets, they make your life very easy.