I\'m trying to reverse a named URL and include a querystring in it. Basically, I\'ve modified the login function, and I want to send ?next=
in it.
Here\'s w
To keep the query optional, you can wrap Django's reverse function with your own function that also handles the query, allowing for other proper handling of the reverse function.
Creating a Proper Request - Note that the query_kwargs
is optional, so you don't have to send it
# from a views in views.py
def sendingView(request, truckID, fleetSlug):
#in the GET or POST
return HttpResponseRedirect(reverse('subAppName:urlViewName',
kwargs={'anyPassedKawrgs':goHere,…},
query_kwargs={'queries': goHere}
))
# from a template in specificTemplate.html
Link
#from a model in models.py
class Truck(models.Model):
name = models.CharField(…)
def get_absolute_wi_url(self):
return reverse('subAppName:urlViewName', kwargs={'kwarg1':kwarg1,'kwarg2':kwarg2})
In utils.py
file (based on docs) for (1.11 and up?)
-myMainApp
-apps
-static
...
-utils
-__init__.py
-utils.py
from django.core.urlresolvers import reverse as django_reverse
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, query_kwargs=None):
"""
Wrapper of django.core.urlresolvers.reverse that attaches arguments in kwargs as query string parameters
"""
if query_kwargs:
return '%s?%s' % (django_reverse(viewname, urlconf, args, kwargs, current_app), \
'&'.join(['%s=%s' % (k,v) for k,v in query_kwargs.items()]))
else:
return django_reverse(viewname, urlconf, args, kwargs, current_app)
In the urls conf urls.py
app_name = 'subAppName'
urlpatterns = [
url(r'^(?P[a-zA-Z0-9]+)/(?P[a-zA-Z0-9]+)/path/to/here/$', views.urlViewFunctionName, name='urlViewName'),
And gaining access to the query
#in a view
def urlViewFunctionName(request, kwarg1, kwarg2):
if request.GET.get('submittedData'):
submittedQuery = request.GET.get('submittedData')
else:
submittedQuery = None
return render(request, 'trucks/weeklyInspectionSuccess.html', {
'truck': truck,
'submittedQuery': submittedQuery
})
#in a template
Success for {{kwarg1}}
{{submittedQuery}}