Home > Mobile >  Build Django URL for export_selected_objects. Example function out of the official django documentat
Build Django URL for export_selected_objects. Example function out of the official django documentat

Time:07-29

I am trying to build an URL that matches the redirect out of this function:

def export_selected_objects(modeladmin, request, queryset):
    selected = queryset.values_list('pk', flat=True)
    ct = ContentType.objects.get_for_model(queryset.model)
    return HttpResponseRedirect('/export/?ct=%s&ids=%s' % (
        ct.pk,
        ','.join(str(pk) for pk in selected),
    ))

That is what I have tried:

from django.urls import path, re_path

from . import views

urlpatterns = [
    re_path(r'^export/(?P<ct>[0-9]{2})/(?P<ids>[0-9]{4})/$', views.test),
    path('export/<int:ct><int:ids>/', views.test),
    path('export/<int:ct>/<int:ids>/', views.test),
    path('export/<ct><ids>/', views.test),
]

But none of these match.

Error Message

Could someone give me a hint about what I'm missing here?

CodePudding user response:

You are generating a URL with query parameters, that looks like this:

/export/?ct=%s&ids=%s

The part from ? onwards is ignored by the URL resolver. Your URL file is expecting a format like this:

/export/<ct>/<ids>/

But the URL you are requesting does not match that and equally nothing in the file matching your URL.

You can either:

a) add path('export/', ...) to your urls.py file

b) change the generated URL string to /export/%s/%s/

  • Related