Django REST: How to use Router in application level urls.py? - python

My Django project structure:
mysite/
mysite/
...
urls.py
scradeweb/
...
models.py
serializers.py
views.py
urls.py
manage.py
If I use Django REST router in the project level urls.py (mysite/urls.py) like below, everything works fine:
# mysite/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from .settings import USER_CREATED_APPS
from rest_framework.routers import DefaultRouter
from scradeweb import views
router = DefaultRouter()
router.register(r'threads', views.ThreadViewSet, )
router.register(r'posts', views.PostViewSet)
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'scradeweb/', include('scradeweb.urls', namespace='scradeweb')),
url(r'^', include(router.urls)),
)
I like keeping all my application (scradeweb) related code within its
directory, so I move router to scradeweb/urls.py:
# scradeweb/urls.py
from django.conf.urls import url, patterns, include
from scradeweb import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'threads', views.ThreadViewSet, )
router.register(r'posts', views.PostViewSet)
urlpatterns = router.urls
When I go to http://127.0.0.1:8000/scradeweb/posts/, it raises the exception:
ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "thread-detail".
You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
Why does it not work?
Here is my scradeweb/models.py
class Thread(models.Model):
thread_id = models.IntegerField()
sticky = models.NullBooleanField()
prefix = models.CharField(max_length=255)
title = models.CharField(max_length=255)
start_time = models.DateTimeField()
author = models.CharField(max_length=255)
url = models.URLField(unique=True)
forum = models.ForeignKey(Forum, related_name='threads')
class Meta:
ordering = ('start_time', )
class Post(models.Model):
post_id = models.IntegerField()
url = models.URLField(unique=True)
post_number = models.IntegerField()
start_time = models.DateTimeField(blank=True)
last_edited_time = models.DateTimeField(blank=True, null=True)
author = models.CharField(max_length=255, blank=True)
content = models.TextField(blank=True)
thread = models.ForeignKey(Thread, related_name='posts')
class Meta:
ordering = ('post_number', )
scradeweb/serializers.py:
from rest_framework import serializers
from scradeweb.models import Thread, Post
class ThreadSerializer(serializers.HyperlinkedModelSerializer):
posts = \
serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='post-detail',
)
class Meta:
model = Thread
fields = ('pk', 'thread_id', 'title', 'url', 'posts')
read_only_fields = ('thread_id', )
class PostSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Post
scradeweb/views.py:
...
class ThreadViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Thread.objects.all()
serializer_class = ThreadSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer

The problem here is that you are using Django REST Framework with a namespace. Many components do not work well with them, which doesn't mean they can't be used, so you need to work around the issues by doing a lot of manual work. The main problem is with hyperlinked relations (Hyperlinked*Fields), because they have to reverse views, and that requires that the namespace is specified.
The first place to start at is the router level, which doesn't currently support namespaces. This is only an issue for the DefaultRouter, as it will build out the index page that contains a list of reversed urls, which will trigger errors right away. This has been fixed in the upcoming release, but for now you're stuck without it. At best (DRF 3.0+), the index page will be completely empty (or point to incorrect urls), in the worst case scenario (DRF 2.x) it will always trigger an internal server error.
The second place to look at is the serializer fields. By default, the HyperlinkedModelSerializer will automatically generate HyperlinkedRelatedField and HyperlinkedIdentityField fields with non-namespaced urls. When you are using namespaces, you have to override all of these automatically generated fields. This generally means you are better off just not using a HyperlinkedModelSerializer, and instead controlling the output with a ModelSerializer.
The first (and easiest) thing to fix is the url field that is automatically generated for all objects. This is automatically generated with view_name set to the detail page (thread-detail in this case), without a namespace. You are going to need to override the view_name and include the namespace in front of it (so scradeweb:thread-detail in this case).
class ThreadSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name="scradeweb:thread-detail",
)
You are also going to need to override all of the automatically generated related fields. This is slightly more difficult for writable fields, but I would always recommend looking at repr(MySerializer()) in those cases to see the arguments for the automatically generated fields. For the case of read-only fields, it's a matter of just copying over the default arguments and changing the view_name again.
class ThreadSerializer(serializers.ModelSerializer):
posts = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='scradeweb:post-detail',
)
This will need to be done for all fields, and it doesn't look like Django REST Framework will be adding the ability to do it automatically in the near future. While this will not be enjoyable at first, it will give you a great opportunity to appreciate everything DRF previously did for you automatically.

I have had the same kind of issue and fix it just change the "HyperlinkedModelSerializer" to "ModelSerializer".
I am just following the rest framework tutorial and got stucked in this part
class TodoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TodoList
fields = '__all__'
to:
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = TodoList
fields = '__all__'

Related

Object has no attribute get in serializer

I created a serializer and an API endpoint so I can retrieve some data from a Django DB in my React app but getting this error message:
AttributeError: 'ProgrammingChallengesView' object has no attribute 'get'
Here is my models.py:
#creating programming challenges
class ProgrammingChallenges(models.Model):
challenge_id = models.AutoField(primary_key=True)
challenge_name = models.CharField(max_length=200)
challenge_description = models.TextField()
challenge_expectations = models.TextField()
my serializer:
from accounts.models import ProgrammingChallenges
...
class ProgrammingChallengesView(serializers.ModelSerializer):
class Meta:
model = ProgrammingChallenges
fields = '__all__'
and my urls.py:
path('api/programming_challenges/', ProgrammingChallengesView, name='programming_challenges'),
Thanks to the comments; I clearly didn't understand that a serializer only transforms my data to make it available through an API. I still had to create a view for my API's endpoint.
I opted to create a ReadOnlyModelView because I only want to GET data from this endpoint.
Here is what I wrote in my views:
class ProgrammingChallengesView(ReadOnlyModelViewSet):
serializer_class = ProgrammingChallengesSerializer
queryset = ProgrammingChallenges.objects.all()
#action(detail=False)
def get_list(self, request):
pass
and in my urls.py:
path('api/programming_challenges/', ProgrammingChallengesView.as_view({'get':'list'}), name='programming_challenges'),
I think you shouldn't hurry read the docs again. You are trying to use serializers as views.
Models - are representation of db tables as class.
Serializer serializes the data to json.
View accepts the reqeust from client and returns a Response.
Code shoudld be:
models.py
class ProgrammingChallenge(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
expectations = models.TextField()
Your model name should be ProgrammingChallenge(singular) not ProgrammingChallenges(plural).
You should't add prefix challenge before all field names. Because we already know that the fields are in a Model called ProgrammingChallenge. And it is easy to access them like ProgrammingChallenge.name than ProgrammingChallenge.challenge_name
You don't have to add field id manually. Django model automatically adds id field as primary_key
serializer.py
from accounts.models import ProgrammingChallenge
...
class ProgrammingChallengeSerializer(serializers.ModelSerializer):
class Meta:
model = ProgrammingChallenge
fields = '__all__'
No problem in serialize.
Now, main problem is you don't have any view. You definetly read docs. You can use APIView, generic views or viewset. In this example i'm going to use ViewSet that handles CRUD operations built in.
viewsets.py
from rest_framework.viewsets import ModelViewSet
from .models import ProgrammingChallenge
from .serializers import ProgrammingChallengSerializer
class ProgrammingChallengViewSet(ModelViewSet):
queryset = ProgrammingChallenge.objects.all()
serializer_class = ProgrammingChallengeSerializer
urls.py
from rest_framework.routers import SimpleRouter
from .viewsets import ProgrammingChallenge
router = SimpleRouter()
router.register('challengr', ProgrammingChallengeViewSet)
urlpatterns = router.urls
Another advantage of using viewset, it also generate all endpoint for it's CRUD methods automatically via routes.
It should help you to start your first project.
AGAIN, READ THE DOCS!

Could not resolve URL for hyperlinked relationship using view name "rest:campaign-detail"

A newbie here in the world of Django. I am struggling with creating a hyperlink for a nested route.
The error I am getting is:
Could not resolve URL for hyperlinked relationship using view name "rest:campaign-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
Some project setup notes
Using django rest framework
using DRF-extensions to create the routes
Using ModelViewSet
Expected end points:
/accounts/
/accounts/< pk >/
/accounts/< pk >/campaigns/
/accounts/< pk >/campaigns/< pk >/
/accounts/< pk >/campaigns/adgroup/
/accounts/< pk >/campaigns/adgroup/< pk >/
Set a namespace of rest in urls.py
Using HyperlinkedIdentityField to create the hyperlink. It only works with the parent object i.e.
url = serializers.HyperlinkedIdentityField(view_name='rest:account-detail')
However fails with any nested object i.e.
url = serializers.HyperlinkedIdentityField(view_name='rest:campaign-detail')
The model is quiet simple, an Account can have many Campaigns, and a campaign can have many AdGroups. See code below:
models.py
from django.db import models
from django.db.models import Q
from model_utils import Choices
ORDER_COLUMN_CHOICES = Choices(
('0', 'id'),
('1', 'keyword'),
('2', 'status'),
('3', 'match_type'),
)
# Account
class Account(models.Model):
account_name = models.CharField(max_length=128)
def __str__(self):
return self.account_name
# Campaign
class Campaign(models.Model):
class Status(models.TextChoices):
Enabled = "Enabled"
Paused = "Paused"
account = models.ForeignKey(
to=Account, on_delete=models.CASCADE, related_name='campaigns'
)
campaign_name = models.CharField(max_length=128)
status = models.CharField(max_length=21, choices=Status.choices, default=Status.Paused)
def __str__(self):
return self.campaign_name
# AdGroup
class AdGroup(models.Model):
class Status(models.TextChoices):
Enabled = "Enabled"
Paused = "Paused"
campaign = models.ForeignKey(
to=Campaign, on_delete=models.CASCADE, related_name='adgroups'
)
adgroup_name = models.CharField(max_length=128)
status = models.CharField(max_length=21, choices=Status.choices, default=Status.Enabled)
def __str__(self):
return self.adgroup_name
views.py
from rest_framework import viewsets
from .serializers import *
from . import models
from rest_framework_extensions.mixins import NestedViewSetMixin
class AccountViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
serializer_class = AccountSerializer
queryset = models.Account.objects.all()
class CampaignViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
serializer_class = CampaignSerializer
queryset = models.Campaign.objects.all()
class AdGroupViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
serializer_class = AdGroupSerializer
queryset = models.AdGroup.objects.all()
serializers.py
from rest_framework import serializers
from . import models
class CampaignSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="rest:campaign-detail")
class Meta:
model = models.Campaign
fields = '__all__'
class AccountSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='rest:account-detail')
class Meta:
model = models.Account
fields = '__all__'
class AdGroupSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='rest:adgroup-detail')
class Meta:
model = models.AdGroup
fields = '__all__'
I have 2 URL files. The project is named Vanilla and an app named rest where the DRF logic sits.
Vanilla urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('rest.urls', namespace='rest')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('admin/', admin.site.urls)
]
Rest urls.py
from django.urls import include, path
from . import views
from rest_framework_extensions.routers import ExtendedSimpleRouter
app_name = 'rest'
router = ExtendedSimpleRouter()
(
router.register(r'accounts',
views.AccountViewSet,
basename='account')
.register(r'campaigns',
views.CampaignViewSet,
basename='campaign',
parents_query_lookups=['account__id'])
.register(r'adgroups',
views.AdGroupViewSet,
basename='adgroup',
parents_query_lookups=['campaign__account', 'campaign'])
Thank You!
use hyperlinkedModelSerializer in all of your related serializer. that should work

Django REST Framework Serializing ForeignKey and ManyToManyFields

I have the following model, which I want serialize for expose via REST:
class RehabilitationSession(models.Model):
patient = models.ForeignKey('userprofiles.PatientProfile', null=True, blank=True,verbose_name='Paciente', related_name='patientprofile')
slug = models.SlugField(max_length=100, blank=True)
medical = models.ForeignKey('userprofiles.MedicalProfile', null=True, blank=True,
verbose_name='Médico tratante')
therapist = models.ForeignKey('userprofiles.TherapistProfile', null=True, blank=True, verbose_name='Terapeuta')
date_session_begin = models.DateTimeField(default=timezone.now(), verbose_name = 'Fecha de inicio')
upper_extremity = MultiSelectField(
max_length=255,
choices=EXTREMITY_CHOICES,
blank=False,
verbose_name='Extremidad Superior'
)
affected_segment = models.ManyToManyField(AffectedSegment,verbose_name='Segmento afectado')
movement = ChainedManyToManyField(
Movement, #Modelo encadenado
chained_field = 'affected_segment',
chained_model_field = 'corporal_segment_associated',
verbose_name='Movimiento'
)
metrics = models.ManyToManyField(Metric, blank=True, verbose_name='Métrica')
date_session_end = models.DateTimeField(default=timezone.now(), verbose_name = 'Fecha de finalización')
period = models.CharField(max_length=25,blank=True, verbose_name='Tiempo de duración de la sesión')
class Meta:
verbose_name = 'Sesiones de Rehabilitación'
def __str__(self):
return "%s" % self.patient
To serialize the fields which are Foreign Key I am reading this documentation
My serializers.py is this:
from .models import RehabilitationSession
from rest_framework import serializers
class RehabilitationSessionSerializer(serializers.HyperlinkedModelSerializer):
patient = serializers.HyperlinkedIdentityField(view_name='patientprofile',)
class Meta:
model = RehabilitationSession
fields = ('url','id','patient',
'date_session_begin','status','upper_extremity',
'date_session_end', 'period','games','game_levels',
'iterations','observations',)
I am using HyperlinkedIdentityField, due to my model is serialized with HyperlinkedModelSerializer but, I don't have clear or I still ignore how to should I serialize when one field is ForeignKey and ManyToManyField
My urls.py main file in which I include the route's for setup the api url's is:
from django.conf.urls import url, include #patterns
from django.contrib import admin
from .views import home, home_files
# REST Framework packages
from rest_framework import routers
from userprofiles.views import UserViewSet, GroupViewSet, PatientProfileViewSet
from medical_encounter_information.views import RehabilitationSessionViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
router.register(r'rehabilitation-session', RehabilitationSessionViewSet)
router.register(r'patientprofile', PatientProfileViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^chaining/', include('smart_selects.urls')),
url(r'^$', home, name='home'),
url(r'^', include('userprofiles.urls')),
#Call the userprofiles/urls.py
url(r'^', include('medical_encounter_information.urls' )),
#Call the medical_encounter_information/urls.py
# which is a regular expression that takes the desired urls and passes as an argument
# the filename, i.e. robots.txt or humans.txt.
url(r'^(?P<filename>(robots.txt)|(humans.txt))$',
home_files, name='home-files'),
#REST Frameworks url's
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
When I try access to url of my api rest, I get the following message in cli:
File "/home/bgarcial/.virtualenvs/neurorehabilitation_projects_dev/lib/python3.4/site-packages/rest_framework/relations.py", line 355, in to_representation
raise ImproperlyConfigured(msg % self.view_name)
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "patientprofile". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
[08/Mar/2016 16:05:45] "GET /api/rehabilitation-session/ HTTP/1.1" 500 165647
And in my browser I get this:
How to can I serialize a ForeignKey and ManyToManyField which happened to me the same situation?
Best Regards
Try changing your serializer to
class RehabilitationSessionSerializer(serializers.HyperlinkedModelSerializer):
patient = serializers.HyperlinkedIdentityField(view_name='patientprofile-detail',)
class Meta:
...
The router automatically creates a detail view with this name for a ViewSet. See docs for parameter view_name:
view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <model_name>-detail.

django1.6 ModelForm Make fields readonly

I have a django model
models.py
class Item(models.Model):
author = models.ForeignKey(User)
name = models.CharField('Brief summary of job', max_length=200)
created = models.DateTimeField('Created', auto_now=True,auto_now_add=True)
description = models.TextField('Description of job')
I would like to update the description field in a modelform using UpdateView. I would like to see the other fields (author,name etc) but want editing and POST disabled
forms.py
from django.forms import ModelForm
from todo.models import Item
class EditForm(ModelForm):
class Meta:
model = Item
fields = ['author', 'job_for', 'name', 'description']
urls.py
urlpatterns = patterns('',
# eg /todo/
url(r'^$', views.IndexView.as_view(), name='index'),
#eg /todo/5
url(r'^(?P<pk>\d+)/$', views.UpdateItem.as_view(), name='update_item'),
)
views.py
class UpdateItem(UpdateView):
model = Item
form_class = EditForm
template_name = 'todo/detail.html'
# Revert to a named url
success_url = reverse_lazy('index')
I have looked at the solution suggesting form.fields['field'].widget.attrs['readonly'] = True but I am unsure where to put this or how to implement
Field.disabled
New in Django 1.9.
The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.
def MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self):
self.fields['field'].disabled = True

Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"

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__"

Categories