Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a url that is using DefaultRouter()?

I'm trying to use reverse() inside my test. I tried this answer! but it's not working.
I still getting the error
django.urls.exceptions.NoReverseMatch: Reverse for 'patients-list' with no arguments not found.

router = DefaultRouter()
router.register(r'patients', views.PatientSet, base_name='patients')

urlpatterns = [
    url(r'^', include(router.urls)),
]

Here is the ModelViewSet

class PatientSet(viewsets.ModelViewSet):
    queryset = Patient.objects.all()
    serializer_class = PatientSerializer
    permission_classes = [IsDoctorUser]
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ['is_active']

I'm using this way inside my test url = reverse('patients-list')

like image 952
RonanFelipe Avatar asked May 08 '19 23:05

RonanFelipe


People also ask

What does the Django urls reverse () function do?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here.

What does it mean to reverse a url?

Just in case you do not know why it is called reverse : It takes an input of a url name and gives the actual url, which is reverse to having a url first and then give it a name.


1 Answers

Firstly, the base_name kwarg to routers is deprecated in favor of the basename kwarg in DRF 3.11, however this should not be what's causing issues. I can't actually see anything wrong with the code sample you've provided either.

What I would recommend is try installing the django-extensions package. After you have installed and configured django-extensions, you can use the python manage.py show_urls command to output a list of all your routes.

python manage.py show_urls

/api/accounts/users/ accounts.views.UserViewSet account:user-list
/api/accounts/users/<uuid>/ accounts.views.UserViewSet account:user-detail

Each line contains the url /api/accounts/users/<uuid>/, the view's path accounts.views.UserViewSet, and the name (this is what you want for reverse) of the route account:user-detail. With this I hope you will be able to find the correct name for your route. The URL portion also indicates any parameters required for that route.

like image 157
A. J. Parr Avatar answered Nov 10 '22 19:11

A. J. Parr