I want to add / remove members from a Team model. Members are specified as a ManyToManyField. I use django-rules to specify permissions, so team owners should be able to add/remove members.
# models.py
from django.db import models
from rules.contrib.models import RulesModel
from django.conf import settings
class Team(RulesModel):
name = models.CharField(max_length=80)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
help_text="Owner can view, change or delete this team.",
related_name="team_owner",
)
members = models.ManyToManyField(
settings.AUTH_USER_MODEL, blank=True, related_name="team_members"
)
The permissions are specified as following:
import rules
#rules.predicate
def is_team_owner(user, obj):
return obj.owner == user
rules.add_perm("teamapp.change_team", is_team_owner)
I've specified some generic views (CreateView, DetailView, UpdateView and DeleteView) to manage the Team. Now I want two separate views to add and remove members on the same.
# views.py
from django.views.generic import (
CreateView,
DetailView,
UpdateView,
ListView,
DeleteView,
)
from rules.contrib.views import PermissionRequiredMixin
from django.contrib.auth import get_user_model
from .models import Team
class TeamMemberAddView(PermissionRequiredMixin, UpdateView):
model = Team
permission_required = "teamapp.change_team"
raise_exception = True
fields = ["members"]
def form_valid(self, form):
user = get_user_model()
new_member = user.objects.get(pk=1)
self.object.members.add(new_member)
return super(TeamMemberAddView, self).form_valid(form)
Which generic view can I use to add / remove members? Which approach is recommended here? I wanted 1 dedicated view to select an existing User to be added, and some links on the list view to delete members. My approach fails, because it does not add members, it only updates to the last User selected. So the ManyToMany table only contains one record.
TL;DR: replace the last line of form_valid by return HttpResponseRedirect(self.get_success_url())
It's important to understand how form_valid of UpdateView works. I recommend to visualize the methods on ccbv.co.uk.
From ModelFormMixin:
If the form is valid, save the associated model.
def form_valid(self, form):
"""If the form is valid, save the associated model."""
self.object = form.save()
return super().form_valid(form)
It means that the object will be saved with the data submitted by the form. UpdateView will restrict the changes to the fields variable:
fields = ["members"]
From FormMixin:
If the form is valid, redirect to the supplied URL.
def form_valid(self, form):
"""If the form is valid, redirect to the supplied URL."""
return HttpResponseRedirect(self.get_success_url())
For your concrete case (add a many-to-many relationship), you need to bypass the model saving from ModelFormMixin by simply returning the supplied URL after adding the relationship (last line changed):
def form_valid(self, form):
user = get_user_model()
new_member = user.objects.get(pk=1)
self.object.members.add(new_member)
return HttpResponseRedirect(self.get_success_url())
Side note: your form seems to provide the member object you want to add, so you could use this instead of including it in the url. Try:
def form_valid(self, form):
for member in form.cleaned_data['members'].all():
self.object.members.add(member.id)
return HttpResponseRedirect(self.get_success_url())
I was using Django users model for my Django rest framework. For this I used Django's ModelViewSet for my User class.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
Serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'password']
extra_kwargs = {
'password' : {
'write_only':True,
'required': True
}
}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
Token.objects.create(user=user) # create token for the user
return user
But currently from postman when I make the request using the token of one user to view, delete, edit other users
http://127.0.0.1:8000/api/users/4/
Its able to edit/delete/view other users. I don't want that to happen and one user can make request on itself only is all I want.
This is my apps urls.py
urls.py
from django.urls import path, include
from .views import ArticleViewSet, UserViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('articles', ArticleViewSet, basename='articles')
router.register('users', UserViewSet, basename = 'users')
urlpatterns = [
path('api/', include(router.urls)),
]
How can I prevent one user from accessing other users when they make GET/POST/PUT/DELETE request.
EDIT 1: After adding the IsOwnerOfObject class as provided in he answers below, now when I am requesting the detail of the user himself, I am getting
Authentication credentials were not provided.
Building from Ene's answer, authentication and permission classes needs to be provided.
Create a file named permissions.py.
from rest_framework import permissions
class IsOwnerOfObject(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return obj == request.user
next add the permission and authentication class to ModelViewSet:
from api.permissions import IsOwnerOfObject
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated, IsOwnerOfObject]
authentication_classes = (TokenAuthentication,)
Create a file named permissions.py.
from rest_framework import permissions
class IsOwnerOfObject(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return obj == request.user
next add the permission class to you ModelViewSet:
from yourapp.permissions import IsOwnerOfObject
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsOwnerOfObject, <other permission classes you want to use>]
More info here:
https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#object-level-permissions
If you want to disable delete completely (Which is probably correct since if you want to "delete" a User you should deactivate it instead.) Then you can replace your view with this:
from rest_framework import viewsets
from rest_framework import generics
class UserViewSet(
generics.CreateModelMixin,
generics.ListModelMixin,
generics.RetrieveModelMixin,
generics.UpdateModelMixin,
generics.viewsets.GenericViewSet
):
queryset = User.objects.all()
serializer_class = UserSerializer
And then you can use Ene Paul's answer to limit who can edit.
Another all-in-one solution could be to use a queryset filter to directly narrow the queryset results. This will prevent an user to delete other users, but also prevent any unauthorized retrieving or listing as the only accessible data will be the user itself only.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
"""
The get_queryset function is used to get the queryset of the user data corresponding to the logged in user.
It is called when the view is instantiated, and it returns a list containing this user only.
"""
# after get all products on DB it will be filtered by its owner and return the queryset
owner_queryset = self.queryset.filter(username=self.request.user.username)
return owner_queryset
And this can also be used with other objects to allow retrieving only data related to this user.
I am building a project in Django Rest Framework where users can login to view their wine cellar.
My ModelViewSets were working just fine and all of a sudden I get this frustrating error:
Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
The traceback shows:
[12/Dec/2013 18:35:29] "GET /bottles/ HTTP/1.1" 500 76677
Internal Server Error: /bottles/
Traceback (most recent call last):
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/viewsets.py", line 78, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 399, in dispatch
response = self.handle_exception(exc)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 396, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/mixins.py", line 96, in list
return Response(serializer.data)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 535, in data
self._data = [self.to_native(item) for item in obj]
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 325, in to_native
value = field.field_to_native(obj, field_name)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 153, in field_to_native
return self.to_native(value)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 452, in to_native
raise Exception(msg % view_name)
Exception: Could not resolve URL for hyperlinked relationship using view
name "user-detail". You may have failed to include the related model in
your API, or incorrectly configured the `lookup_field` attribute on this
field.
I have a custom email user model and the bottle model in models.py is:
class Bottle(models.Model):
wine = models.ForeignKey(Wine, null=False)
user = models.ForeignKey(User, null=False, related_name='bottles')
My serializers:
class BottleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Bottle
fields = ('url', 'wine', 'user')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'password', 'is_superuser')
My views:
class BottleViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows bottles to be viewed or edited.
"""
queryset = Bottle.objects.all()
serializer_class = BottleSerializer
class UserViewSet(ListCreateAPIView):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
and finally the url:
router = routers.DefaultRouter()
router.register(r'bottles', views.BottleViewSet, base_name='bottles')
urlpatterns = patterns('',
url(r'^', include(router.urls)),
# ...
I don't have a user detail view and I don't see where this issue could come from. Any ideas?
Thanks
Because it's a HyperlinkedModelSerializer your serializer is trying to resolve the URL for the related User on your Bottle.
As you don't have the user detail view it can't do this. Hence the exception.
Would not just registering the UserViewSet with the router solve your issue?
You could define the user field on your BottleSerializer to explicitly use the UserSerializer rather than trying to resolve the URL. See the serializer docs on dealing with nested objects for that.
I came across this error too and solved it as follows:
The reason is I forgot giving "**-detail" (view_name, e.g.: user-detail) a namespace. So, Django Rest Framework could not find that view.
There is one app in my project, suppose that my project name is myproject, and the app name is myapp.
There is two urls.py file, one is myproject/urls.py and the other is myapp/urls.py. I give the app a namespace in myproject/urls.py, just like:
url(r'', include(myapp.urls, namespace="myapp")),
I registered the rest framework routers in myapp/urls.py, and then got this error.
My solution was to provide url with namespace explicitly:
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="myapp:user-detail")
class Meta:
model = User
fields = ('url', 'username')
And it solved my problem.
Maybe someone can have a look at this : http://www.django-rest-framework.org/api-guide/routers/
If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. For example:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include(router.urls, namespace='api')),
]
you'd need to include a parameter such as view_name='api:user-detail' for serializer fields hyperlinked to the user detail view.
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:user-detail")
class Meta:
model = User
fields = ('url', 'username')
Another nasty mistake that causes this error is having the base_name unnecessarily defined in your urls.py. For example:
router.register(r'{pathname}', views.{ViewName}ViewSet, base_name='pathname')
This will cause the error noted above. Get that base_name outta there and get back to a working API. The code below would fix the error. Hooray!
router.register(r'{pathname}', views.{ViewName}ViewSet)
However, you probably didn't just arbitrarily add the base_name, you might have done it because you defined a custom def get_queryset() for the View and so Django mandates that you add the base_name. In this case you'll need to explicitly define the 'url' as a HyperlinkedIdentityField for the serializer in question. Notice we are defining this HyperlinkedIdentityField ON THE SERIALIZER of the view that is throwing the error. If my error were "Could not resolve URL for hyperlinked relationship using view name "study-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field." I could fix this with the following code.
My ModelViewSet (the custom get_queryset is why I had to add the base_name to the router.register() in the first place):
class StudyViewSet(viewsets.ModelViewSet):
serializer_class = StudySerializer
'''custom get_queryset'''
def get_queryset(self):
queryset = Study.objects.all()
return queryset
My router registration for this ModelViewSet in urls.py:
router.register(r'studies', views.StudyViewSet, base_name='studies')
AND HERE'S WHERE THE MONEY IS! Then I could solve it like so:
class StudySerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="studies-detail")
class Meta:
model = Study
fields = ('url', 'name', 'active', 'created',
'time_zone', 'user', 'surveys')
Yep. You have to explicitly define this HyperlinkedIdentityField on itself for it to work. And you need to make sure that the view_name defined on the HyperlinkedIdentityField is the same as you defined on the base_name in urls.py with a '-detail' added after it.
This code should work, too.
class BottleSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
class Meta:
model = Bottle
fields = ('url', 'wine', 'user')
Today, I got the same error and below changes rescue me.
Change
class BottleSerializer(serializers.HyperlinkedModelSerializer):
to:
class BottleSerializer(serializers.ModelSerializer):
I ran into this error after adding namespace to my url
url('api/v2/', include('api.urls', namespace='v2')),
and adding app_name to my urls.py
I resolved this by specifying NamespaceVersioning for my rest framework api in settings.py of my project
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.NamespaceVersioning'}
TL;DR: It may be as simple as removing a trailing 's' from the router basename. No need to define a url field in your serializer.
For the original poster, the issue was resolved simply by registering the UserViewSet, as suggested in the top answer.
However, if anyone else has this issue even with all ViewSets registered, I think I've figured out what's going wrong, and I've found a solution that's cleaner than a lot of the others here.
In my case, I encountered this issue after trying to create a ViewSet with a custom get_queryset() function. When I replaced the ViewSet's queryset field with a custom get_queryset() function, I was then hit with this error:
AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.
So, of course, I went to urls.py and modified my registration to include a basename as such:
router.register(r'messages', MessageViewSet, basename='messages')
But then I was hit with this error (as we see in the original post):
Could not resolve URL for hyperlinked relationship using view name "message-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
After reading the DRF docs on routers, I learned that the router automatically generates two url patterns for you, which have names:
'basename-list'
'basename-detail'
Because I set my basename='messages' (note the 's' at the end), my url patterns were named:
'messages-list'
'messages-detail'
Since DRF was looking a url pattern named 'message-detail' (note here the lack of 's'), I realized that I could resolve this simply by removing the trailing 's' from my basename as such:
router.register(r'messages', MessageViewSet, basename='message')
My final serializer and ViewSet implementations were as simple as this!
class MessageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Message
fields = ['url', 'message', 'timestamp', 'sender', ...]
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
def get_queryset(self):
return Message.objects.filter(...)
It appears that HyperlinkedModelSerializer do not agree with having a path namespace. In my application I made two changes.
# rootapp/urls.py
urlpatterns = [
# path('api/', include('izzi.api.urls', namespace='api'))
path('api/', include('izzi.api.urls')) # removed namespace
]
In the imported urls file
# app/urls.py
app_name = 'api' // removed the app_name
Hope this helps.
Same Error, but different reason:
I define a custom user model, nothing new field:
from django.contrib.auth.models import (AbstractUser)
class CustomUser(AbstractUser):
"""
custom user, reference below example
https://github.com/jonathanchu/django-custom-user-example/blob/master/customuser/accounts/models.py
# original User class has all I need
# Just add __str__, not rewrite other field
- id
- username
- password
- email
- is_active
- date_joined
- method, email_user
"""
def __str__(self):
return self.username
This is my view function:
from rest_framework import permissions
from rest_framework import viewsets
from .models import (CustomUser)
class UserViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.AllowAny,)
serializer_class = UserSerializer
def get_queryset(self):
queryset = CustomUser.objects.filter(id=self.request.user.id)
if self.request.user.is_superuser:
queryset = CustomUser.objects.all()
return queryset
Since I didn't give queryset directly in UserViewSet, I have to set base_name when I register this viewset. This is where my error message caused by urls.py file:
from myapp.views import (UserViewSet)
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'users', UserViewSet, base_name='customuser') # <--base_name needs to be 'customuser' instead of 'user'
You need a base_name same as your model name - customuser.
If you're extending the GenericViewSet and ListModelMixin classes, and have the same error when adding the url field in the list view, it's because you're not defining the detail view. Be sure you're extending the RetrieveModelMixin mixin:
class UserViewSet (mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
A bit late but in Django 3 and above, include doesn't support namespace without specifying the app_name. Checking the source code for include, we see that the condition
if namespaces and not app_name:
....
is checked. And still from the source code, app_name is gotten like;
urlconf_module, app_name = arg
where arg is the first argument of the include. This tells us that, our include should be defined as
include((app.urls, app_name), namespace='...')
Example
Say you have a project myproject and an app myapp. Then you want to establish an address. You should use a viewset and define a router as below
myapp.urls
router.register('address', exampleviewset, basename='address')
myproject.urls
path('api/v1/', include(('myapp.urls', 'myapp'), namespace='myapp')),
serializers.py
class AddressSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="myapp:address-detail")
class Meta:
model = Address
fields = ('url',...)
Apparently, we can't use fields='__all__'. We must include url explicitly and list the remaining fields we need.
I ran into the same error while I was following the DRF quickstart guide
http://www.django-rest-framework.org/tutorial/quickstart/ and then attempting to browse to /users. I've done this setup many times before without problems.
My solution was not in the code but in replacing the database.
The difference between this install and the others before was when I created the local database.
This time I ran my
./manage.py migrate
./manage.py createsuperuser
immediately after running
virtualenv venv
. venv/bin/activate
pip install django
pip install djangorestframework
Instead of the exact order listed in the guide.
I suspected something wasn't properly created in the DB. I didn't care about my dev db so I deleted it and ran the ./manage.py migrate command once more, created a super user, browsed to /users and the error was gone.
Something was problematic with the order of operations in which I configured DRF and the db.
If you are using sqlite and are able to test changing to a fresh DB then it's worth an attempt before you go dissecting all of your code.
Bottle = serializers.PrimaryKeyRelatedField(read_only=True)
read_only allows you to represent the field without having to link it to another view of the model.
I got that error on DRF 3.7.7 when a slug value was empty (equals to '') in the database.
I ran into this same issue and resolved it by adding generics.RetrieveAPIView as a base class to my viewset.
I was stuck in this error for almost 2 hours:
ImproperlyConfigured at /api_users/users/1/
Could not resolve URL for hyperlinked relationship using view name "users-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
When I finally get the solution but I don't understand why, so my code is:
#models.py
class Users(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50, blank=False, null=False)
email = models.EmailField(null=False, blank=False)
class Meta:
verbose_name = "Usuario"
verbose_name_plural = "Usuarios"
def __str__(self):
return str(self.name)
#serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Users
fields = (
'id',
'url',
'name',
'email',
'description',
'active',
'age',
'some_date',
'timestamp',
)
#views.py
class UserViewSet(viewsets.ModelViewSet):
queryset = Users.objects.all()
serializer_class = UserSerializer
#urls_api.py
router = routers.DefaultRouter()
router.register(r'users',UserViewSet, base_name='users')
urlpatterns = [
url(r'^', include(router.urls)),
]
but in my main URLs, it was:
urlpatterns = [
url(r'^admin/', admin.site.urls),
#api users
url(r'^api_users/', include('usersApi.users_urls', namespace='api')),
]
So to finally I resolve the problem erasing namespace:
urlpatterns = [
url(r'^admin/', admin.site.urls),
#api users
url(r'^api_users/', include('usersApi.users_urls')),
]
And I finally resolve my problem, so any one can let me know why, bests.
If you omit the fields 'id' and 'url' from your serializer you won't have any problem. You can access to the posts by using the id that is returned in the json object anyways, which it makes it even easier to implement your frontend.
I had the same problem , I think you should check your
get_absolute_url
object model's method input value (**kwargs) title.
and use exact field name in lookup_field
It is worth noting that if you create an action with detail=False (typo?) then this errors will be raised, replace it with detail=True:
#action(detail=True)
...
I wanted to stay with everything as-is out of the box so I just added a User serializer:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['id', 'username']
A Viewset:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
And added to urls:
router.register(r'users', UserViewSet)
From DRF Docs:
drf docs note source
Note: If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as view_name='app_name:user-detail' for serializer fields hyperlinked to the user detail view.
The automatic view_name generation uses a pattern like %(model_name)-detail. Unless your models names actually clash you may be better off not namespacing your Django REST Framework views when using hyperlinked serializers.
Solution
example of setting view_name
from rest_framework import serializers
from myapp.models import Post
from django.contrib.auth.models import User
class PostSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:post-detail")
author = serializers.HyperlinkedRelatedField(view_name="api:user-detail", read_only=True)
viewers = serializers.HyperlinkedRelatedField(view_name="api:user-detail", read_only=True, many=True)
class Meta:
model = Post
fields = ('id', 'title', 'url', 'author', 'viewers')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"