custom URLs using django rest framework

2024/10/7 20:31:24

I am trying to use the django rest framework to expose my models as APIs.

serializers

class UserSerializer(serializers.HyperlinkedModelSerializer):class Meta:model = User

viewset

class UserViewSet(viewsets.ModelViewSet):"""API end point for User details and list"""serializer_class = UserSerializerqueryset = User.objects.all()

routers

router.register(r'users',views.UserViewSet)

While this exposes /users/ and users/, I want my URLs to include a user-slug as well, something like /users/1/xyz-user-name.

Has anyone solved this problem? Does this need changes in both the viewset and router code or is it something that can be configured only in the router code? MY "slug" isn't really used for determining url routing, it is only for URL readability.

Any pointers?

Answer

I was able to get this to work by using the approach posted here.

django-rest-framework HyperlinkedIdentityField with multiple lookup args

The second error I was receiving was becuase I was including the url definition inside the meta section. It should be before the meta section instead. I also had to specify the lookup field in the viewset code. Here are the relevant parts of my code.

urls.py

from user.views import UserViewSet
user_list = UserViewSet.as_view({'get':'list'})
user_detail = UserViewSet.as_view({'get':'retrieve'})urlpatterns= [url(r'^users/$', user_list, name='user-list'),url(r'^user/(?P<id>\d+)/(?P<slug>[-\w\d]+)/$', user_detail, name='user-detail'),url(r'^api-auth/', include('rest_framework.urls',namespace = 'rest_framework'))
]

views.py:

class UserViewSet(viewsets.ModelViewSet):"""API end point for user details and user list"""lookup_field = 'id'serializer_class = UserSerializerqueryset = user.objects.all()

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):url = ParameterisedHyperlinkedIdentityField(view_name='user-detail', lookup_fields=(('id', 'id'), ('slug', 'slug')), read_only=True)class Meta:model = userfields = ('url','name','cover_photo')
https://en.xdnf.cn/q/70198.html

Related Q&A

Does python logging.FileHandler use block buffering by default?

The logging handler classes have a flush() method. And looking at the code, logging.FileHandler does not pass a specific buffering mode when calling open(). Therefore when you write to a log file, it …

Non brute force solution to Project Euler problem 25

Project Euler problem 25:The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be F1 = 1, F2 = 1, F3 = 2, F4 = 3, F5 =…

python:class attribute/variable inheritance with polymorphism?

In my endeavours as a python-apprentice i got recently stuck at some odd (from my point of view) behaviour if i tried to work with class attributes. Im not complaining, but would appreciate some helpfu…

Unable to load firefox in selenium webdriver in python

I have installed Python 3.6.2, Selenium 3.5.0 with GeckoDriver 0.18.0 and the firefox version is 54.0.1version on windows 7. I am trying to run a selenium script which is loading a firefox where i get …

Plot hyperplane Linear SVM python

I am trying to plot the hyperplane for the model I trained with LinearSVC and sklearn. Note that I am working with natural languages; before fitting the model I extracted features with CountVectorizer …

Calculating plugin dependencies

I have the need to create a plugin system that will have dependency support and Im not sure the best way to account for dependencies. The plugins will all be subclassed from a base class, each with i…

Vectorization: Not a valid collection

I wanna vectorize a txt file containing my training corpus for the OneClassSVM classifier. For that Im using CountVectorizer from the scikit-learn library. Heres below my code: def file_to_corpse(file…

Solve a simple packing combination with dependencies

This is not a homework question, but something that came up from a project I am working on. The picture above is a packing configuration of a set of boxes, where A,B,C,D is on the first layer and E,F,G…

ImportError: cannot import name FFProbe

I cant get the ffprobe package to work in Python 3.6. I installed it using pip, but when I type import ffprobe it saysTraceback (most recent call last): File "<stdin>", line 1, in <m…

Generate larger synthetic dataset based on a smaller dataset in Python

I have a dataset with 21000 rows (data samples) and 102 columns (features). I would like to have a larger synthetic dataset generated based on the current dataset, say with 100000 rows, so I can use it…