i'm creating like button for my django blog i import api to use ajex from django rest frameworks but i'm getting error in that the error is get() got an unexpected keyword argument 'pk' django
class PostLikeToggle(RedirectView):
def get_redirect_url(self, *args, **kwargs):
obj = get_object_or_404(Post, pk=kwargs['pk'])
url_ = obj.get_absolute_url()
user = self.request.user
if user.is_authenticated:
if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)
return url_
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
class PostLikeApiToggle(APIView):
authentication_classes = [authentication.SessionAuthentication]
permission_classes = [permissions.IsAuthenticated]
def get(self, request, format=None):
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
def get_redirect_url(self, *args, **kwargs):
obj = get_object_or_404(Post, pk=kwargs['pk'])
url_ = obj.get_absolute_url()
user = self.request.user
updated = False
liked =False
if user.is_authenticated:
if user in obj.likes.all():
liked = False
obj.likes.remove(user)
else:
liked = True
obj.likes.add(user)
updated = True
data = {
"updated":updated,
"liked":liked
}
return Response(data)
path('blog/<int:pk>/like/', PostLikeToggle.as_view(),name='Like-Toggle'),
path('blog/api/<int:pk>/like/', PostLikeApiToggle.as_view(),name='Like-Api-Toggle'),
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User,on_delete=models.CASCADE)
likes =models.ManyToManyField(User,blank=True,related_name='post_likes')
content = models.TextField()
img = models.ImageField(upload_to='pics',blank=True)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('LoveTravel-Details', kwargs={'pk': self.pk})
def get_like_url(self):
return reverse('Like-Toggle', kwargs={'pk':self.pk})
def get_api_like_url(self):
return reverse('Like-Api-Toggle', kwargs={'pk':self.pk})
can someone please help me get() got an unexpected keyword argument 'pk' in that error
The error is quite explicit. The get
method is missing an argument.
In order to fix that:
class PostLikeApiToggle(APIView):
...
def get(self, request, pk, format=None):
Why did you get that error ?
Your urls.py
defines the path as 'blog/<int:pk>/like/'
. Django will resolve that url and call the view's method - get in your case - with the group names/values as keyword arguments - refer to the point 4 of the documentation for more details about how Django processes requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With