I realize stackoverflow does a trick with the url for making it more human readable
It has the following pattern
stackoverflow.com/questions/id_question/title_question
for example we have
stackoverflow.com/questions/36676286/counter-with-lambda-over-map-java8
And if you delete part of the title question and you go to the url left
Example : stackoverflow.com/questions/36676286/counter-with-la
You are still redirect to the correct url.
Looks it only reads until the id, and then it adds the title info to the url , how I could add this information to the url?
Thanks in advance
You can achieve this by capturing both id and slug in the URL but only using the id to look up the post; then you can compare the post's slug with the one you got, and redirect if they are not equal. Something like (using Django 2.0 path syntax):
path('questions/<int:id>/<slug:slug>', views.question, 'question')
...
def question(request, id, slug=None):
post = Post.objects.get(id=id)
if slug != post.slug:
return redirect('question', id=id, slug=post.slug)
...
Related
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.
So I am struggling a bit, with something that logically seems so simple but due to my limited understanding of Django I am not sure where to look and how to formulate a solution.
Basically I have a Blog app set up and it shows the complete(all the content including disqus discussion) latest post on the home page. The post has a further link to the posts own page as well. I have set up Disqus and need to get some key information to use for the disqus_url and disqus_identifier. I have set up the model as follows with a method for get_absolute_url as follows:
def get_absolute_url(self):
return reverse('blog.views.renderBlog',args=[str(self.id),str(self.slug)])
My view is set up as follows:
def renderBlog(request,postid=1,slug=None):
template = 'blog_home.html'
if(postid == 1 and slug == None):
post = Post.objects.latest('date_created')
else:
post = Post.objects.get(slug=slug, id=postid)
data = {
'post':post,
}
return render(request, template, data)
As you can see the view is set up to handle both URL's as follows:
url(r'^$', 'renderBlog', name='blogHome'),
url(r'^post/(?P<postid>\d{1,4})/(?P<slug>[\w-]+)/$', 'renderBlog', name='blogPostPage'),
In my template I am setting disqus_identifier = '{{ post.get_absolute_url }}' and I am hardcoding the domain portion in the meantime as disqus_url = 'http://127.0.0.1{{ post.get_absolute_url }}';.. Same goes for the comment count <a href="" data-disqus-identifier.
I dont like doing things in a hackish manner, what would be the best method for me to get the full absolute url. I have looked at request.get_absolute_uri but am not sure on how to actually use it to get what I want.
Thanks
The way I like to do it is configure a context_processor:
from django.contrib.sites.models import Site
def base_context_processor(request):
return {
'BASE_URL': "http://%s" % Site.objects.get_current().domain
}
# or if you don't want to use 'sites' app
return {
'BASE_URL': request.build_absolute_uri("/").rstrip("/")
}
in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'path.to.base_context_processor',
...
)
(In newer versions of Django, modify context_processors under TEMPLATES, OPTIONS instead.)
then in templates:
Object Name
Another solution would be to use request.build_absolute_uri(location), but then you would have to create a template tag that takes a request object and a location or an object that has get_absolute_uri method. Then you would be able to use it templates like that: {% get_full_uri request=request obj=post %}. Here is documentation on how to write custom tags.
This question is pretty old but I think its still relevant.
To get_absolute_url with domain in Django template you can do the following:
<li>Home</li>
First check if the request is https or not and then get the request of the host and pass the absolute url.
This way you will get full URL with domain in Django template.
I know the question is old, but I'm not sure the best answer provided is the correct one.
You should just use
as the Django docs point out.
https://docs.djangoproject.com/en/4.0/ref/models/instances/#get-absolute-url
The url provided comes with the domain as well.
Regards
How to validate the url if some change the name in url and update the form,
Suppose :
If i want to update a profile ,after click on the update button.ulr link will be like below
url : http://localhost:8000/profile_edit/sushanth/
i found there is an security loop here,a person can change the name on the url and he can edit other person profile,how to close this loop hole while updating the form in django.
Thanks in advance...:)
You just need to check in your view that the user is the correct one.
#login_required
def profile_edit(request, username):
if username != request.user.username:
return HttpResponseNotAllowed()
Is it possible to use urls names in views, like we can do it in template?
Check out the docs on reverse
They have a specific example reversing a named url here:
https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls
reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
viewname is either the function name
(either a function reference, or the
string version of the name, if you
used that form in urlpatterns) or the
URL pattern name.
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls
(Updated answer to point to an existing url.)
I know this topic is years old, however during my own search for the same, this one popped up. I believe the requester is looking for the following in views.py:
views.py
class Overview(ListView):
model = models.data
template_name = "overview.html"
def get_queryset(self):
name = self.request.resolver_match.url_name
print(name)
Do note that I'm using class based views. Within regular views, the name can be retrieved as follows (not tested):
def current_url_name(request):
html = "<html><body>Url name is {}.</body></html>".format(request.resolver_match.url_name)
return HttpResponse(html)
The url name is within the (self.)'request' variable. From within your view, 'resolver_match.url_name' is the one you're looking for.
Hope this helps people in search of the same.
<script>
var salesApiUrl = "{% url 'URLNamesHere' %}"
</script>
Now, the salesApiUrl is global. You can use the var name in js as well
I have a purchase page, it can take an optional argument as a gift, if it is a gift, the view passes a gift form to the template and if not, a regular purchase form.
my old regular url, which redirects to two seperate views:
(r'^(?P<item>[-\w]+)/purchase/$', 'purchase_view'),
(r'^(?P<item>[-\w]+)/purchase/gift$', 'gift_view'),
and the views was like this:
def purchase_view(request,item):
....use purchase form
def gift_view(request,item):
....use giftform
It is a bad design indeed, as both views having are almost everything same but the forms used.
I have also thougt about using GET and giving gift as a GET param however it wasnt a good idea as I am using POST method for these pages, especially would cause issue after validation.
How can I make this a single url and a single view?
Thanks
urls.py
url(r'^(?P<item>[-\w]+)/purchase/$', 'purchase_view', name='purchase_view'),
url(r'^(?P<item>[-\w]+)/purchase/(?P<gift>gift)/$', 'purchase_view', name='gift_view'),
views.py
def purchase_view(request, item, gift=False):
if gift:
form = GiftForm
else:
form = PurchaseForm
...