When i add product to my home function in views.py I got this error :
No product matches the given query.
image
Why do I get this error?
views:
class productviewset(viewsets.ModelViewSet):
queryset=product.objects.all()
serializer_class = productSerializer
def create(self, request):
serialized = productSerializer(data=request.data, many=True)
if serialized.is_valid():
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
#action (detail=False , methods=['post'])
def delete(self,request):
product.objects.all().delete()
return Response('success')
def home(request ):
p=get_object_or_404(product,pk=1)
return render(request,'home.html',{'p':p})
def foods(request):
return render(request,'foods.html',{'p':category.objects.all()})
models:
class category(models.Model):
name=models.CharField(max_length=255, db_index=True)
def __str__(self):
return self.name
class product(models.Model):
category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE)
image=models.CharField(max_length=500)
description=models.CharField(max_length=500)
price=models.CharField(max_length=50)
buy=models.CharField(max_length=100)
urls:
from django.urls import include, path
from rest_framework import routers
from quick.views import productviewset
from quick import views
from django.contrib import admin
urlpatterns = [
path('api/', include(router.urls)),
path('',views.home),
path('foods',views.foods),
path('admin/',admin.site.urls),
]
Try like this:
views.py
def home(request, id):
p=get_object_or_404(product, id=id)
return render(request,'home.html',{'p':p})
urls.py
urlpatterns = [
...
path('<int:id>/', views.home, name='name'),
]
Note: Always add / at the end of every route.
Note: Models in django are written in PascalCase not smallcase, it will be better if you change it from category and product to Category and Product respectively.
Class based views are also written in PascalCase, you can change it to ProductViewSet.
๐จ I desperately need #classmethod
i am use this code:
from rest_framework.response import Response
class MyClass():
#classmethod
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
def CRUD(cls, request, id=0):
#.....
return Response({})
urlpatterns = [
re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', UserView.CRUD)
]
get error:
The 'request' argument must be an instance of 'django.http.HttpRequest', not 'builtins.type'.
please help ; Thankful๐๐ป๐๐ป
Like #404pio said. Either you use a class based view or function based view. You cannot mix them.
class-based-view
from rest_framework.response import Response
from rest_framework.views import APIView
class MyClass(APIView):
def get(self, request, id):
# do stuff
return Response(...)
def post(self, request, id):
# do stuff
return Response(...)
.
.
.
urlpatterns = [
re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', MyClass.as_view())
]
or
function-based-view
#api_view(['GET', 'POST'...])
def my_fbv(request, id):
if request.method == 'GET':
# do stuff
elif request.method == 'POST':
# do stuff
.
.
.
urlpatterns = [
re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', my_module.my_fbv)
]
it was necessary to combine several models(4) in one serializer, but there were problems with the implementation.
urls.py
from django.urls import path
from .views import FiltersView
urlpatterns = [
path('filters/' FiltersView.as_view(), name='Filters')
]
views.py
from rest_framework import views
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from .serializers import FiltersSerializers
class FiltersView(views.APIView):
def get(self, request, *args, **kwargs):
filters = {}
filters['model_1'] = Model1.objects.all()
filters['model_2'] = Model2.objects.all()
filters['model_3'] = Model3.objects.all()
serializer = FiltersSerializers(filters, many=True)
return Response (serializer.data, status=HTTP_200_OK)
serializers.py
from rest_framework import serializers
class FiltersSerializers(serializers.Serializer):
model_1 = Model1Serializers(read_only=True, many=True)
model_2 = Model2Serializers(read_only=True)
model_3 = Model3Serializers(read_only=True)
But on the output I get:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{},
{},
{}
]
What could be the problem?
The way you are providing data to your serializer, many=True is not correct argument for it. Its a single object that you are passing to your serializer. Your view should be like this.
class FiltersView(views.APIView):
def get(self, request, *args, **kwargs):
filters = {}
filters['model_1'] = Model1.objects.all()
filters['model_2'] = Model2.objects.all()
filters['model_3'] = Model3.objects.all()
serializer = FiltersSerializers(filters)
return Response (serializer.data, status=HTTP_200_OK)
I have an django app,But i want to make its API so just i created it
after runing the server
Page not found (404)
But my django app is running,After the running the url of API i got the error of Page not found
List/views.py
from django.http import Http404
from django.shortcuts import render
from django.views.generic import ListView,DetailView
from .models import List
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from List.serializers import ListSerializers
class MainListView(ListView):
queryset = List.objects.all()
# temp = List.objects.all()
template_name = "main_list.html"
def get_context_data(self, *args, **kwargs):
context = super(MainListView, self).get_context_data(*args, **kwargs)
context['temp'] = List.objects.all()
return context
class MainListView(ListView):
queryset = List.objects.all()
# temp = List.objects.all()
template_name = "List/list.html"
def get_context_data(self, *args, **kwargs):
context = super(MainListView, self).get_context_data(*args, **kwargs)
context['temp'] = List.objects.all()
return context
class MainDetailSlugView(DetailView):
queryset = List.objects.all()
template_name = "news/detail.html"
#csrf_exempt
def head_list(request):
if request.method == 'GET':
queryset = List.objects.all()
serializer = ListSerializer(queryset, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = ListSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
#csrf_exempt
def head_detail(request, pk):
try:
head = List.objects.get(pk=pk)
except List.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = ListSerializer(list)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(head, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
head.delete()
return HttpResponse(status=204)
List/urls.py
from django.urls import path
from List import views
from .views import(
# ListlistView,
MainListView,
MainDetailSlugView,
head_list,
head_detail
)
urlpatterns = [
# url(r'^$',ListlistView.as_view()),
path('',MainListView.as_view(),name='list'),
path('(<pk>\d+)(?:/(<slug>[\w\d-]+))',MainDetailSlugView.as_view(), name='List'),
path('list/',views.list_list),
path('lists/<int:pk>/',views.list_detail),
]
List/serializers.py
from rest_framework import serializers
from List.models import List
class ListSerializers(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=True, allow_blank=False,max_length=120)
slug = serializers.SlugField(required=False,)
description= serializers.CharField(required=True, allow_blank=False)
image = serializers.ImageField(required=True,)
timestamp = serializers.DateTimeField(required=True,)
code = serializers.CharField(style={'base_template': 'textarea.html'})
language = serializers.CharField(default='python')
style = serializers.CharField(default='friendly')
def create(self, validated_data):
return List.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.descritption = validated_data.get('descritption', instance.descritption)
instance.image = validated_data.get('image', instance.image)
instance.timestamp = validated_data.get('timestamp',instance.timestamp)
instance.language = validated_data.get('language',instance.language)
instance.style = validated_data.get('style',)
instance.save()
return instance
List/models.py
import random
import os
from django.db import models
from django.urls import reverse
from django.db.models.signals import pre_save, post_save
from lokswar.utils import unique_slug_generator
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
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())
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name,ext
def upload_image_path(instence, filename):
new_filename = random.randint(1,396548799)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext= ext)
return "card/{new_filename}/{final_filename}".format(new_filename=new_filename,
final_filename=final_filename)
class ListQuerySet(models.query.QuerySet):
def active(self):
return self.filter(active=True)
class ListManager(models.Manager):
def get_queryset(self):
return ListQuerySet(self.model, using=self._db)
def all(self):
return self.get_queryset().active()
class List(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
description= models.TextField()
image = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
code = models.TextField(default=True)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
objects = ListManager()
class Meta:
ordering = ('created',)
def get_absolute_url(self):
return reverse('List', kwargs={'pk': self.pk, 'slug': self.slug })
def __str__(self):
return self.title
def __unicode__(self):
return self.title
Please help me to solve this error.
I am trying to run my API through this url http://127.0.0.1:8000/List/list/
urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from .views import HomeListView
urlpatterns = [
path('List',include('List.urls'), name="List"),
path('news/',include('news.urls'), name="news"),
path('', HomeListView.as_view(), name='home'),
path('sports/',include('sports.urls'), name="sports"),
path('movie/',include('movie.urls'), name="movie"),
path('business/',include('business.urls'), name="business"),
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
]
You make a small mistake in url at url.py file.
Change:
path('List',include('List.urls'), name="List"),
Into:
path('List/',include('List.urls'), name="List"),
urlpatterns = [
path('',MainListView.as_view(),name='list'),
path('(<pk>\d+)(?:/(<slug>[\w\d-]+))',MainDetailSlugView.as_view(), name='List'),
path('list/',views.list_list),
path('lists/<int:pk>/',views.list_detail),
]
As you can see above, you have two urls defined that apply here
/list/
/lists/<int> # which applies to something like /lists/293749
you're URL calling is /List/list, which doesn't apply to any URLs here unless you define a project-level URLs.py with something like
urlpatterns = [
path('list/', include('List.urls'))
]
Couple things:
Take a look at python conventions. Classes are capitalized and PascalCase whereas variables, methods and functions are snake_case. No reason for you to have a module capitalized
Don't use the same names as python/django builtins and reserved words. That causes issues and is a good habit to get into.
I believe django treats urls as case sensitive when they come in the URL parser. You call /List, but the url definition is /list
I have a Django rest api which you can upload a file and an id:
Screenshot
I want to call a function when post button is pressed in order to do some stuff with the uploaded file. How can I do this in django rest platform?
models.py
from django.db import models
from .validators import validate_file_extension
class Uplist(models.Model):
report_id = models.CharField(max_length=200, primary_key= True)
application = models.FileField(blank=False, null=False, validators=[validate_file_extension])
serializers.py
from rest_framework import serializers
from api import models
class UplistSerializer(serializers.ModelSerializer):
class Meta:
model = models.Uplist
fields = ('application', 'report_id',)
urls.py
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.ListUps.as_view()),
url(r'^$', views.ListUps.as_view()),
url(r'^(?P<pk>[0-9]+)/$', views.ListDetails.as_view()),
]
views.py
from rest_framework import generics
from rest_framework.parsers import MultiPartParser, FormParser
from api import models
from . import serializers
class ListUps(generics.ListCreateAPIView):
parser_classes = (MultiPartParser, FormParser)
queryset = models.Uplist.objects.all()
serializer_class = serializers.UplistSerializer
class ListDetails(generics.RetrieveUpdateDestroyAPIView):
queryset = models.Uplist.objects.all()
serializer_class = serializers.UplistSerializer
validators.py
def validate_file_extension(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
valid_extensions = ['.csv']
if not ext.lower() in valid_extensions:
raise ValidationError(u'Unsupported file extension.')
In urls add pattern
path('someurl', SomeClass.as_view()),
In your view.py
class SomeClass(generics.ListCreateAPIView):
def post(self, request, **kwargs):
....
When you call post function you goto this view. You can perform your tasks here.
Answer:
class ListUps(generics.ListCreateAPIView):
parser_classes = (MultiPartParser, FormParser)
queryset = models.Uplist.objects.all()
serializer_class = serializers.UplistSerializer
def post(self, request, *args, **kwargs):
#added function here
return self.create(request, *args, **kwargs)