Django - issue with APPEND_SLASH and POST requests - django

I am using Django 1.10, and my goal now is to make urls available both with and without trailing slash. To do this, I added slash to all my URLs in the URLConf files, and then set APPEND_SLASH variable value to True (well, this is the default value).
Now the problem is that external POST requests (which I can't control) yield the following error:
You called this URL via POST, but the URL doesn't end in a slash and
you have APPEND_SLASH set. Django can't redirect to the slash URL
while maintaining POST data. Change your form to point to
127.0.0.1:8000/Calendar/AddAccounts/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
They mention this in Django doc, and yet after hours of surfing the net, I can't figure out how to address this issue.
I've also come across this question, but the proposed solution doesn't seem acceptable to me. It says I have to make the users call my URLs only with trailing slash. While I know that in other languages (C# for example) it is possible to enable both options

It seems weird to me that you want to support both cases. Ideally you would want to redirect from non slash to slash(or the other way around if you want that) on the server level (nginx/apache/whatever you use) before the request hits Django.
Just choose a strategy and stick to it, so add the trailing slash to your form and never look back. :)
It's important to be consistent. https://www.branded3.com/blog/urls-trailing-slash-seo/

If the urls are used for APIs or the SEO is not important to you, you can consider both with slash and without slash by adding "/?". In django 3.X:
from django.urls import re_path
re_path(r'^query/?$', 'search.views.query'),
re_path(r'^add/?$', 'search.views.add'),
In Restframework routers:
from rest_framework.routers import DefaultRouter
class CustomDefaultRouter(DefaultRouter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.trailing_slash = '/?'
router = CustomDefaultRouter()
router.register('link', ViewSet, basename='link')

Related

Urlpatterns: category/subcategory/article-slug

Django==3.2.5
re_path(r'^.*/.*/<slug:slug>/$', Single.as_view(), name="single"),
Here I'm trying to organize the following pattern: category/subcategory/article-slug. Category and subcategory are not identifying anything in this case. Only slug is meaningful.
Now I try:
http://localhost:8000/progr/django/1/
And get this:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/progr/django/1/
Using the URLconf defined in articles_project.urls, Django tried these URL patterns, in this order:
admin/
^.*/.*/<slug:slug>/$ [name='single']
articles/
^static/(?P<path>.*)$
^media/(?P<path>.*)$
The current path, progr/django/1/, didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
What can I do to resolve this?
You are mixing the path and re_path functions, re_path has no path converters and only uses regex, hence when you write <slug:slug> that literally means a url having that exact string there, instead you want to capture the pattern [-a-zA-Z0-9_]+ (which is the pattern Django uses for a slug). Also using .* in your pattern will likely cause you problems, as it can match / too and likely cause some of your other urls to be never used, instead you might want to use [^/]*. So you likely want to change your pattern to:
re_path(r'^[^/]*/[^/]*/(?P<slug>[-a-zA-Z0-9_]+)/$', Single.as_view(), name="single"),
This still feels a little problematic to me as it matches two arbitrary patterns and doesn't capture and pass them to the view, you might in fact simply want to shift to using path and capture these patterns too:
from django.urls import path
path('<str:some_string1>/<str:some_string2>/<slug:slug>/', Single.as_view(), name="single"),

DRF post url without end slash

In my application , I need to display the REST url(s) without a slash at the end. I have tried below combination but it didnt work.
Added APPEND_SLASH=True in the settings.py
and on the urls.py file
from rest_framework.routers import SimpleRouter
router = SimpleRouter(trailing_slash=False)
After adding this when I am calling the urls without slash at the end in the postman, it is giving me an 404 error- URL not found. But with slash at the end is working fine.
Is there any option to make this url without with slash at the end ? Especially for the post urls
APPEND_SLASH will append it to the request (e.g. mysite/blog --> mysite/blog/). This is not what you want, since your urlconf explicitly says there should be no slash.
Also APPEND_SLASH is True by default. So you need to set it to False instead. That way, if you make a request without a slash, Django won't automatically add in a slash.

404 on a simple template view - strange

I have a django app set up consisting of ListViews, TemplateViews etc..
So, I just added a small templateview to it like so:
#views.py
class TermsTemplateView(TemplateView):
template_name = "terms.html"
#urls.py
url(r'^terms/$', TermsTemplateView.as_view(), name='terms'),
and in terms.html, I am using for linking:
Terms & Conditions
For some strange reason, I keep getting 404 on localhost/terms as follows:
404: No <model_name> found matching the query
I am baffled why this is happening all of a sudden. I have the same set up for "about", "thanks", "contact" pages, and they seem to display it with no problems.
..and the worst part is, if I modify the urls.py like so:
url(r'^/terms/$', TermsTemplateView.as_view(), name='terms'),
and then go to http://127.0.0.1:8000//terms/ - the page seems to be there.. I am surprised why this is so :(
Any help would enlighten me!
The / at the end is the culprit of your problems. localhost/terms doesn't match '^terms/$' regular expression, localhost/terms/ does.
You can make / at the end optional by using ?:
url(r'^terms/?$', TermsTemplateView.as_view(), name='terms'),
UPD: Note that there is a better solution to the problem, APPEND_SLASH:
When set to True, if the request URL does not match any of the
patterns in the URLconf and it doesn’t end in a slash, an HTTP
redirect is issued to the same URL with a slash appended.
Also see:
Why would you need a slash at the end of a URL?
django - url with automatic slash adding
Append Slashes to URLs in Django

Django url dispatcher page not found

i am trying to define a url pattern in django urls.py like
url(r'^networking$','mysite1.networking.views.networking'),
when i am typing http://myhost.com/networking in my address bar to go to networking page
i am getting 404 error and a slash '/' automatically added to the address bar like
http://myhost.com/networking/
help me out what i am doing wrong?
You probably aren't including your urlconf correctly. The behavior you're seeing is because of APPEND_SLASH is set to True by default when Django can't resolve the url.
Either set Append_Slash to false which is true by default or use your url description like given below which redirect url with slash to desired view.
url(r'^networking/$','mysite1.networking.views.networking'),
Seems your Apache server or some Django middleware is adding trailing slashes. You can either correct that, or the better way is you can use the following url pattern:
url(r'^networking/?$','mysite1.networking.views.networking'),

redirect rule for nginx?

I am running my django app using nginx. I want to write a redirect rule such that
if user hit the url http://example.com/django/nginx/ then it redirect it to
http://example.com/django/#!/nginx/. I want o know the regex for it.
Thanks
You'll want to handle this on the client side (through Javascript, most likely), not through nginx.
From what I understand, the point of # in URLs (as per the spec) is that the portion that comes after # doesn't reach the server.
Also, see this question for some info on JS libraries for working with hash-bang urls: Are there any javascript libraries for working with hashbang/shebang (#!) urls?
Given you example I'm assuming that you are working with URLs in the form "http://1/2/3/" only, so nothing going beyond 3. Where you want to separate 2 and 3 with "/#!/". If that is the case you can try the following.
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
('^django/(?P<ajax_section>\w+)/$', redirect_to, {'url': '/django/#!/%(ajax_section)s/'}),
)
The above assumes that 2("django") in the URL will be fixed. If that is not the case you will have to try and make it a parameter as well.