passing url matching parameter to reverse() in urls.py - django

in my urls.py I need to invoke a generic CreateView that requires a success_url parameter. The "success" URL contains an identifier that I need to pass to the reverse() URL search function. I get this parameter from the URL of the CreateView. please see the code below. I need to grab the value of the <pk> parameter in the "create" url, and pass it on to the "success" url. how is this done?
thanks
konstantin
PS: using django trunk
...
url(r'^path/(?P<pk>\d+)/apply/$',
generic.CreateView.as_view(form_class=MyForm,
success_url=reverse_lazy('success', args=[???<pk>???]),
template_name='create.html'), name='create'),
url(r'path/(?P<pk>\d+)/apply/success/$',
generic.TemplateView.as_view(template_name='success.html'), name='success'),
...

This is explained in the documentation:
success_url may contain dictionary string formatting, which will be interpolated against the object's field attributes. For example, you could usesuccess_url="/polls/%(slug)s/" to redirect to a URL composed out of the slug field on a model.

Related

django url _reverse _ not a valid view function or pattern name

the redirect url is
"liveinterviewList/2"
and, ofcourse, I declare that url in url.py
more over, when I type that url in browser manualy, it works well.
what's the matter?
more question.
at this case, I write the user_id on the url.
I think, it is not good way to make url pattern.
but I don't know how I deliver the user_id variable without url pattern.
please give me a hint.
What HariHaraSudhan left out was how to use parameters. For your case, you would want something like:
path(r'liveinterviewList/<int:userId>', ..., name='live-interview'),
And then when you are ready to reverse, use this:
reverse('app:live-interview', kwargs={ 'userId': userId })
where app is the name of the app in which your view lives. If your url lives in the main urls file , you don't need the app: prefix.
Django reverse function accepts the name of the path not the URL.
lets say i have url patterns like this
urlpatterns = [
path('/users/list', name="users-list")
]
In my view i can use like this
def my_view(request):
return redirect(reverse("users-list"));
You should add a name to your path url and use it to redirect.
As the django doc says :
urls :
urlpatterns = [
path('/name', name="some-view-name")
]
def my_view(request):
...
return redirect('some-view-name')

redirect vs reverse django

I have experienced using reverse within get_absolute_url method in the model, but I wish I have an idea about the difference between reverse and redirect, I have tried to search on google about it but there is almost nothing
I don't know what should I write also to convince stack overflow that I don't have any other description
Reverse and redirect have a different meaning. Here is a simple explanation:
reverse in Django is used to find the URL of a given resource. Let's say that you have a blog website and from the main page, you want to provide links to your blog posts. You can of course just hard-code /posts/123/ and just change the ID of your blog post in URL, but that makes it hard to change your URL for the post in the future. That's why Django comes with reverse function. All you need to do is to pass the name of your URL path (defined in your urlpatterns) and Django will find for you the correct URL. It is called reverse because it is a reverse process of determining which view should be called for a given URL (which process is called resolving).
Redirects are not specific to Django or any other web frameworks. Redirect means that for a given URL (or action), the user should be instructed to visit a specific URL. This can be done by sending a special redirect request and from there the browser will handle it for the user, so no user action is required in that process. You can use reverse in redirect process to determine the URL that the user should be redirected to.
GwynBleidD has given you the answer, but there is a reason why you might be getting confused. The Django redirect shortcut accepts arguments in several different forms. One of them is a URLpattern mane, with arguments, that is then passed to reverse to generate the actual URL to redirect to. But that's just a shortcut, to enable a common pattern.
here's an example
app/views
#imports
def indexView(request):
....
return render(request, 'index.html', context)
def loginView(request):
....
return redirect('index')
def articleDetailView(request, id):
....
return redirect(reverse('article-comments', kwargs={'id':id})
def articleCommentsView(request, id):
....
return render(request, 'comment_list.html', context)
proj/urls
#imports
urlpatterns = [
....,
path('', include(app.urls))
]
app/urls
#imports
urlpatterns = [
....,
path('index/', index, name='index'),
path('login/', loginView, name='login'),
path('article/<int:id>/detail', articleDetailView, name='article-detail'),
path('article/<int:id>/comments/',articleCommentsView, name='article-comments')
....,
]
For loginView redirect will return url as-is i.e. 'index' which will be appended to base(project) urlpatterns. Here redirect(reverse('index')) will also work since kwargs is None by default for reverse function and 'index' view doesn't require any kwarg. It returns '/index/' which is passed to redirect(which again will be appended to base urls).
One thing to note is that reverse is used to make complete url - needed for redirect - that is shown in 'articleDetailview'.
The most basic difference between the two is :
Redirect Method will redirect you to a specific route in General.
Reverse Method will return the complete URL to that route as a String.

Url maps operation in Django

i'm new to django and i'd like to know how the url maps work in detail.
from django.conf.urls import url
from polls import views
urlpatterns =[
url(r'^$',views.index,name='index')
]
the url function takes 3 parameters, could you explain how they work and what functionalies they have.
I've searched for this, but no detailed information are available for an absolute beginner
The Django URL dispatcher contains urlpatterns which is a Python list of url() instances.
The url(regex, view, kwargs=None, name=None) function can take 4 arguments:
regex: Regular expression, pattern matching the url.
view: View name, path, function or the result of as_view() for class-based views. It can also be an include().
kwargs: Allows you to pass additional arguments to the view function or method.
name: Naming URL patterns.

Providing parameters when reverse_lazy-ing a success_url redirect

TLDR: I want to be able to provide slug in reverse_lazy('view', kwargs={'slug':'my_page'}) like this: reverse_lazy('view').apply(kwargs={'slug':'my_page'}), after creating the lazy object.
I have the following url pattern that includes a slug to identify a page model instance:
url(r'^(?P<slug>'+settings.SLUG_PATTERN+')/$', views.MyView.as_view(), name='view'),
I have another view for editing the page:
url(r'^(?P<slug>'+settings.SLUG_PATTERN+')/_edit/$',
views.MyEditView.as_view(success_url=reverse_lazy('view')), name='edit'),
Note the addition of success_url so that when I submit the form with the new content I'm redirected to the now-edited page. In case I ever change my view url pattern I don't have to worry about updating the redirect for my edit url.
After the form is validated and saved, the view grabs the success url to be used in a HttpResponseRedirect. However just the name 'view' isn't enough to identify the URL. I also need to know the slug name which is stored in my page model's slug field.
A similar question is here: success_url in UpdateView, based on passed value
The answers suggest writing a custom get_success_url for every view, but there must be better approaches.
In the generic views in django's edit.py there's this:
url = self.success_url.format(**self.object.__dict__)
If success_url were given as a hard coded URL but with a slug identifier such as '{slug}/' this would replace it with the slug field in my model. That's very close to what I want, but I don't want to hard code my URL. This brings me to my question:
How can I pass in parameters to a reverse_lazy object? I would use this in my base view's get_success_url with self.object.__dict__ and it'd just work everywhere.
Moreover if my slug string was stored on separate Slug model I might want the success URL to be '{slug.name}/'. With the above approach I could supply a mapping between the URL parameters and model attributes:
redirect_model_mapping = {'slug': '{slug.name}'}
...
def get_success_url(self):
url = self.success_url
if is_a_lazy_redirect(url):
url = url.somehow_apply_parameters(redirect_model_mapping)
return url.format(**self.object.__dict__)
I would like somehow_apply_parameters to be equivalent to originally calling reverse_lazy('blog:view', kwargs=redirect_model_mapping). However I don't think this should be in urls.py because it shouldn't have to know about the mapping.
This is a hack, but does what I want...
class MyView(FormMixin, ...):
#this is actually set on child classes
redirect_model_mapping = {'slug':'{slug.name}'}
def get_success_url(self):
url = self.success_url
if url is not None:
if hasattr(self.success_url, '_proxy____kw'):
url_parameters = dict((k, v.format(**self.object.__dict__)) for k, v in six.iteritems(self.redirect_model_mapping))
url._proxy____kw = {'kwargs': url_parameters}
url = force_text(url)
else:
url = url.format(**self.object.__dict__)
else:
raise ImproperlyConfigured("No URL to redirect to.")
return url
It replaces the kwards parameter normally passed to reverse_lazy but after it actually has the values it needs. As reverse_lazy also requires the string to match the regex, I had to make the mapping between url parameters and the values in the models first.
I'd quite like an approach that doesn't need to write to _proxy____kw.

Pass a query parameter with django reverse?

I have a url that is meant to be accessed like
/people/raj/updates
/people/raj/updates?tag=food
But Django reverse URL resolver seems to have no provision to do tag=food, that is to detect it as an extra parameter and put in the query string.
How do I pass query parameters?
It depends on whether you are building the URL in the python code or in a template.
In python code (e.g. the view):
from django.http import QueryDict
query_dictionary = QueryDict('', mutable=True)
query_dictionary.update(
{
'tag': 'food'
}
)
url = '{base_url}?{querystring}'.format(
base_url=reverse(my.url.name),
querystring=query_dictionary.urlencode()
)
And in a template:
My Link
You caould also pass the QueryDict object from the view to the template and use that when building the URL in the template:
My Link
Django's reverse does not include GET or POST parameters. They are not part of the url.
You can of course always create the url by, for instance in a template, attaching the parameter as in:
{% url 'named_url' %}?tag=food
This way it gets attached anyway. Alternative is building an url regex that includes the possible tag, like:
url(r'^/people/raj/updates/(?P<tag>[a-zA-Z0-9]+/)?', yourview())
This way you can check for the kwarg tag in your view.