Home > front end >  Is it possible to pass the foreign key id in Django rest-framework URL?
Is it possible to pass the foreign key id in Django rest-framework URL?

Time:03-29

I am using routers in Django Rest Framework and trying to create a dynamic URL based on a foreign key. My urls.py file looks like this,

router = routers.DefaultRouter()
router.register('user/<int:user_id>/profile', ProfileViewSet, 'profile')

urlpatterns = router.urls

My models.py file looks like below,

class Profile(models.Model):
    user = models.ForeignKey(
        User, related_name='profile_user', on_delete=models.CASCADE)
    character = models.CharField(max_length=10, null=True, blank=True)

My views.py file looks like below,

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

I am getting the 404 error in all (post, put, get) request. Is there any possible easy solution for such kind of implementation?

Edit

This is my resulting URL (GET request):

http:localhost:8000/user/1/profile

And I am getting the following result:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/user/1/profile

CodePudding user response:

Change this line

router.register('user/<int:user_id>/profile', ProfileViewSet, 'intensity_classes')

Use this

router.register(r'users', ProfileViewSet, basename='user')

Then for list view

http://127.0.0.1:8000/users/ -> List of profiles

For detail view

http://127.0.0.1:8000/users/13 ->here 13 is the profile id, you can update, delete the Profile instance

CodePudding user response:

After changing the URL in regex format, my issue was solved. Instead of this,

router.register('user/<int:user_id>/profile', ProfileViewSet, 'profile')

I wrote this,

router.register(r'user/(?P<user_id>\d )/profile', ProfileViewSet, 'profile')
  • Related