I have been trying to emulate comment functionality with a decorator.
import json
import jwt
from django.views import View
from django.http import JsonResponse
from functools import wraps
from django.db.models import Q
from .models import Comment
from account.models import Account
class CommentView(View):
def login_required(func):
#wraps(func)
def wrapper(request, *args, **kwargs):
# import pdb; pdb.set_trace()
given_token = json.loads(request.body)['access_token']
decoded_token = jwt.decode(given_token,None,None)
try:
if Account.objects.filter(username=decoded_token).exists():
return func(request, *args, **kwargs)
return JsonResponse({"message": "username does not exist"})
except KeyError:
return JsonResponse({"message": "INVALID_KEYS"}, status=403)
return wrapper
#login_required
def post(self, request):
print("request ", json.loads(request.body))
data = json.loads(request.body)
Comment.objects.create(
username = jwt.decode(json.loads(request.body)['access_token']),
content = data['content'],
)
return JsonResponse({"message":"Comment Created!"}, status=200)
def get(self, request):
return JsonResponse({'comment':list(Comment.objects.values())}, status=200)
And I used the program called Httpie to give JSON POST request like so:
http -v http://127.0.0.1:8000/comment access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJlY2sifQ.2unop67pLHOshcGs385GwOvaZZW_J--TRNXyHI3gKNU" content="hello"
There is no problem with the token since this is the exact copy of the token give during the SignInView(which is in another app).
Below is the models.py file in the 'comment' app.
from django.db import models
from account.models import Account
class Comment(models.Model):
username = models.ForeignKey(Account, on_delete=models.CASCADE)
content = models.TextField()
created_time= models.DateTimeField(auto_now_add = True)
updated_time= models.DateTimeField(auto_now = True)
class Meta:
db_table = 'comments'
def __str__(self):
return self.username + ": " + self.content
However, when I send the POST request with the Httpie like above, I get this error:
Internal Server Error: /comment
Traceback (most recent call last):
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/woohyunan/miniconda3/auth/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/Users/woohyunan/projects/Wecode/westagram/KillaGramz-backend/comment/views.py", line 19, in wrapper
given_token = json.loads(request.body)['access_token']
AttributeError: 'CommentView' object has no attribute 'body'
[20/May/2020 17:35:40] "POST /comment HTTP/1.1" 500 73224
I have been wondering what would cause the error. I wonder if there is no way to put the json request body into the decorator which would allow me to decode the token(the decoded version will be the username) so that I can see if it matches with the username in the database.
Thank you so much!!
I solved the problem!
def wrapper(request, *args, **kwargs):
needs to be
def wrapper(self, request, *args, **kwargs):
Related
Hello I would like help I have been trying to learn how to create token with django rest framework and pyjwt
But whenever I do it when I am going to use login it gives me an error I would like to know if it is due to the code since I have seen several videos and I have the same code or it is due to something on my computer and if so, how could I solve it, the error is the next
Internal Server Error: /api/login
Traceback (most recent call last):
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "D:\Users\ferna\Documents\Cursos\Youtube\auth.env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:\Users\ferna\Documents\Cursos\Youtube\auth\users\views.py", line 37, in post
token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'
[07/May/2021 21:18:23] ←[35;1m"POST /api/login HTTP/1.1" 500 96900←[0m
the code for view it's
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import AuthenticationFailed
from .serializers import UserSerializer
from .models import User
import jwt, datetime
# Create your views here.
class RegisterView(APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
class LoginView(APIView):
def post(self, request):
email = request.data['email']
password = request.data['password']
user = User.objects.filter(email=email).first()
if user is None:
raise AuthenticationFailed('User not found!')
if not user.check_password(password):
raise AuthenticationFailed('Incorrect password!')
payload = {
'id': user.id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'iat': datetime.datetime.utcnow()
}
token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')
response = Response()
response.set_cookie(key='jwt', value=token, httponly=True)
response.data = {
'jwt': token
}
return response
I found actual problem.
The package PyJWT changed return type of jwt.encode(...) with version 2. From now it returns string instead of byte string. Link
After that use these codes:
encoded = jwt.encode({"some": "payload"}, key, algorithm="HS256")
result = jwt.decode(encoded, key, algorithms="HS256")
instead of that this:
result = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')
I use slugify to create slugs for my blog's posts urls. In order to accept in the slug also non english characters (greek), I overrode Post model's save() method, with one that includes a parameter allow_unicode=True. However that couldn't work in admin area. Whenever I tried to set a greek characters slug in admin area either by setting a new post with greek title, or by editing the english slug of an existing post, admin form wouldn't allow me to save. For that, as I found in other threads, I should override the save_model() method in admin.py file. So I did, but I get an error. Now the error I get points out that admin area requested the post whose slug is going to change with the old url (an id based one), instead of the slug-url I set in the urls.py.
The error I get is either an AttribureError at /admin/blog/post/1 (when I'm editing the slug of an existing post), or an AttribureError at /admin/blog/post/add (when I'm adding a new post). And the exception value in both cases is 'WSGIRequest' object has no attribute 'save'
How should I set admin-side save methods to request the urls using slug urls?
Thank you in advance!
models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from ckeditor.fields import RichTextField
from django.utils.text import slugify
from taggit.managers import TaggableManager
class Post(models.Model):
title = models.CharField(max_length=100)
content = RichTextField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
is_published = models.BooleanField(default=True)
slug = models.SlugField(unique=True, max_length=100)
tags = TaggableManager(blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title, allow_unicode=True)
super(Post, self).save(*args, **kwargs)
admin.py:
from django.contrib import admin
from .models import Post
from django.utils.text import slugify
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'slug', 'is_published', 'author', 'date_posted')
list_editable = ('is_published',)
def save_model(self, request, obj, form, change):
if not obj.slug:
obj.slug = slugify(obj.title, allow_unicode=True)
super(PostAdmin, self).save_model(self, request, obj, form)
admin.site.register(Post, PostAdmin)
urls.py:
from django.urls import path, register_converter, re_path
from .views import (
PostListView,
UserPostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
TagIndexView
)
from django.urls.converters import SlugConverter
class CustomSlugConverter(SlugConverter):
regex = '[-\w]+'
register_converter(CustomSlugConverter, 'custom_slug')
urlpatterns = [
path('front_page', PostListView.as_view(), name='blog-home'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
re_path(r'post/(?P<slug>[\w-]+)/$', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
re_path(r'post/(?P<slug>[\w-]+)/update$', PostUpdateView.as_view(), name='post-update'),
re_path(r'post/(?P<slug>[\w-]+)/delete$', PostDeleteView.as_view(), name='post-delete'),
path('tag/<slug>', TagIndexView.as_view(), name='tag-posts'),
]
EDIT: Here is the error traceback:
Traceback (most recent call last):
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 614, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 233, in inner
return view(request, *args, **kwargs)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1656, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1534, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1580, in _changeform_view
self.save_model(request, new_object, form, not add)
File "/home/george/PythProj/myWebsite/blog/admin.py", line 15, in save_model
super(PostAdmin, self).save_model(self, request, obj, form)
File "/home/george/PythProj/myWebsite/myws_venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1093, in save_model
obj.save()
Exception Type: AttributeError at /admin/blog/post/1/change/
Exception Value: 'WSGIRequest' object has no attribute 'save'
EDIT2: The solution to avoid the error was of course to write my super() method in a correct way. However that didn't give to my code the functionality I wanted. So what seems to be the solution to my problem, is to declare the slug in my model as a CharField, instead of SlugField. In that case I can even remove my save_model() method that was the reason for the post. Now I'm checking if is going to be any side effect of removing the SlugField. If not I should find the thread I saw that solution to give the credit, if there are side effects I should restore SlugField and find a way to override its validate_slug class. That's all, thank you guys for your response!
EDIT3: Hadn't notice that allow_unicode=True could be argument not only for slugify(), but also for models.SlugField()... So that was for me the final solution...
when you call super() method, you should not pass self there as a parameter. So instead of your current code:
def save_model(self, request, obj, form, change):
super(PostAdmin, self).save_model(self, request, obj, form)
you should call the super() without self as a parameter, and add the missing change on the end:
def save_model(self, request, obj, form, change):
super(PostAdmin, self).save_model(request, obj, form, change)
I am trying to make a notifications app. I have a middle that collects info about the action the user should be notified about and in the view that handles the action it automatically creates an instance in the UserNotification model. This is all working. Now, if a user's post gets liked by another user, that actions needs to be displayed on the notifications page. However, I obviously don't want any one use to be able to see every notification that is being created on the site, but rather only the notifications that are created by their posts.
I am running into an issue with the view and filtering the notifications based on the current user. More specifically, I am getting this error:
AttributeError at /notify/notify/
'UserNotifications' object has no attribute 'user'
With traceback:
Traceback (most recent call last):
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch
return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/list.py", line 160, in get
self.object_list = self.get_queryset()
File "/Users/garrettlove/Desktop/evverest/notify/views.py", line 30, in get_queryset
return UserNotification.objects.filter(user=request.user)
Here is my view pertaining to this:
// Bunch of imports are all here
User = get_user_model()
class UserNotifications(LoginRequiredMixin,ListView):
login_url = 'account_login'
model = UserNotification
template_name = 'notify/usernotification_list.html'
context_object_name = 'notifies'
paginate_by = 25
def get_queryset(request):
return UserNotification.objects.filter(user=request.user)
Here is my UserNotification model:
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
User = get_user_model()
# Create your models here.
class UserNotification(models.Model):
user = models.ForeignKey(User,related_name='user',null=True)
post = models.ForeignKey('feed.UserPost',related_name='post')
timestamp = models.DateTimeField(auto_now_add=True)
notify_type = models.CharField(max_length=6)
read = models.BooleanField(default=False)
def __str__(self):
return str(self.user)
def get_queryset(self):
return UserNotification.objects.filter(user=self.request.user)
I'm currently working on the following issue: The user can access the page test.com/BlogPostTitle. Where BlogPostTitle is a slug. If a Blog post with the fitting title exists, Django should render the DetailView of said blog post. If it doesn't exist, Django should render a form to create a blog post.
This works so far:
class EntryDetail(DetailView): # Displays blog entry, if it exists
model = Blog
slug_field = 'title'
template_name = 'app/entry.html'
class EntryForm(FormView): # Displays form, if entry 404s
template_name = 'app/create.html'
form_class = EntryForm
success_url = '/'
def form_valid(self, form):
form.save()
return super(EntryForm, self).form_valid(form)
class EntryDisplay(View):
def get(self, request, *args, **kwargs):
try:
view = EntryDetail.as_view()
return view(request, *args, **kwargs)
except Http404:
if check_user_editor(self.request.user) == True: # Fails here
view = EntryForm.as_view()
return view(request, *args, **kwargs)
else:
pass
Now, only users who are in the group "editor" should be able to see the form/create a post:
def check_user_editor(user):
if user:
return user.groups.filter(name="editor").exists() # Returns true, if user in editor group
else:
return False⋅
As you can see, I've implemented the function in the EntryDisplay, however, Django errors 'User' object is not iterable.
I'm guessing I've to work with SingleObjectMixin, but I haven't quite understood the docs on that.
Any help would be much appreciated.
Full traceback:
Traceback:
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/detail.py" in get_object
53. obj = queryset.get()
File "/home/django/local/lib/python3.4/site-packages/django/db/models/query.py" in get
385. self.model._meta.object_name
During handling of the above exception (Blog matching query does not exist.), another exception occurred:
File "/home/django/mediwiki/mediwiki/views.py" in get
68. return view(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/detail.py" in get
115. self.object = self.get_object()
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/detail.py" in get_object
56. {'verbose_name': queryset.model._meta.verbose_name})
During handling of the above exception (No blog found matching the query), another exception occurred:
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/django/mediwiki/mediwiki/views.py" in get
74. view = HttpResponse(request.user)
File "/home/django/local/lib/python3.4/site-packages/django/http/response.py" in __init__
293. self.content = content
File "/home/django/local/lib/python3.4/site-packages/django/http/response.py" in content
319. content = b''.join(self.make_bytes(chunk) for chunk in value)
File "/home/django/local/lib/python3.4/site-packages/django/utils/functional.py" in inner
235. return func(self._wrapped, *args)
Exception Type: TypeError at /test
Exception Value: 'User' object is not iterable
Your error is in line 74 in mediwiki.views:
view = HttpResponse(request.user)
HttpResponse expects a string or an iterable. Since request.user is not a string, it tries to use it as an iterable, which fails.
I can't say much without the actual code. If in fact you want to send just a string representation of the user as the response, you need to cast is to a string:
view = HttpResponse(str(request.user))
Is the error occurred at template rendering? If so I wonder you've make iter over attributes on single User object. I think you may need user.values().
BTW, check_user_editor should be simpler:
def check_user_editor(user):
return user.groups.filter(name="editor").exists()
While learning Django rest framework, I got a AssertionError at /tasks/1 error
Expected view TaskDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.
My model.py
class Task(models.Model):
owner=models.ForeignKey('auth.User',related_name='tasks')
completed=models.BooleanField(default=False)
title=models.CharField(max_length=100)
description=models.TextField()
serializer.py
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
read_only=('owner.username',)
fields=('title','description','completed','owner.username')
permission.py
class IsOwnerOrReadOnly(BasePermission):
def has_object_permission(self, request, view, obj):
if request.method is SAFE_METHODS:
return True
return obj.owner==request.user
views.py
class TasksMixins(object):
queryset = Task.objects.all()
serializer_class=TaskSerializer
permission_classes=(IsOwnerOrReadOnly,)
def pre_save(self,obj):
obj.owner=self.request.user
class TaskList(TasksMixins,ListCreateAPIView):
pass
class TaskDetail(TasksMixins,RetrieveUpdateDestroyAPIView):
pass
Urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^tasks/$', views.TaskList.as_view(), name='task_list'),
url(r'^tasks/(?P<id>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
]
Traceback
Traceback (most recent call last):
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 286, in get
return self.retrieve(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 56, in retrieve
instance = self.get_object()
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 93, in get_object
(self.__class__.__name__, lookup_url_kwarg)
AssertionError: Expected view TaskDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.
When ever I navigate to the link I get this error
Any help is much appreciated...Thanks in advace
error image
If you want to target by 'pk', just rename id -> pk into your url.py:
url(r'^tasks/(?P<pk>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
If you want to target by other field than pk,, you have to adjust the url.py, the view.py AND the serializer.py precising a lookup_field (that can be Nested) for example, it could be for you.
url.py:
url(r'^tasks/(?P<owner__username>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
view.py:
class TasksMixins(object):
queryset = Task.objects.all()
serializer_class=TaskSerializer
permission_classes=(IsOwnerOrReadOnly,)
lookup_field = 'owner__username'
serializer.py
class TaskSerializer(serializers.ModelSerializer):
owner = serializers.SlugRelatedField(slug_field='username',many=False, read_only=True)
class Meta:
model = Task
fields='__all__'
lookup_field = 'owner__username'