difference between URL and path in Django? - python

I just started learning Django, and not able to understand that what is the actual difference between URL and path in Django.

Until Django 1.11 there was nothing called a path to define app urls. Django 2.0 introduces path as a replacement for URL. Since you have just started with Django stick with 2.0 documentation and keep in mind that every forum you check will have solutions for older versions of Django

I know that this is an older question, but to answer the question directly:
Since Django 2.0, the url() function is an alias to django.urls.re_path()
And, it is listed as deprecated since Django 3.1.
So, you should use either path() or re_path() moving forward, depending on which meets your needs.

HTTP URLs are defined in section 3.3 of RFC 1738:
An HTTP URL takes the form:
http://<host>:<port>/<path>?<searchpart>
Given a URL such as https://www.djangoproject.com/download/, the path is just /download/.
Sadly, Django often confuses paths and URLS. For example, all of the code examples for the get_absolute_url() method in the documentation return paths, not URLs.
Some parts of Django do get it right though, such as request.path and request.build_absolute_uri() which use the correct terms.

Related

What template is loaded by Django?

I was following Django tutorial, and got stuck where it asked me to replace the default template for administrative part of the site with my own. The problem was a typo in the template's name. I suspected there must be a problem like that, but to troubleshoot the problem it'd be very helpful to see some kind of report from Django on what template it used to render a particular page. Is there any way to do this?
First if you have set DEBUG = True django automatically gives you information about where django was looking for templates (in general and especially in case it didn't find one)
You should see something like this:
second you can add the popular django plugin django-debug-toolbar. It can show you for each request what templates were used and what their context was.
see: https://django-debug-toolbar.readthedocs.io/en/stable/panels.html#template
Still, not exactly the answer, but something to get me closer. One could start Django shell, and then try this:
>>> from django.template.loader import get_template
>>> get_template('template/name').origin.name
to find out what template was actually used. This is still not enough to see though which templates were considered while resolving the template.

Why django urls end with a slash?

Django official documentation and other tutorials on the web always use a trailing slash at the end of url. ex:
url(r'^accounts/login/', views.login) # login view in turn calls login.html
# instead of
url(r'^accounts/login', views.login)
Since accounts is the directory and login (login.html) is the file, shouldn't we be using second url? This will also make GET parameters look more structured:
accounts/login?name='abc' # login is a file that is accepting parameters
vs.
accounts/login/?name='abc' # login directory (maybe index) is accepting parameters??
One of Django’s core design philosophies is URLs should be beautiful.
So some url like accounts/detail?name='abc' should be mapped as accounts/detail/abc/. You can capture it using regex at your url configurations. Here the URL is pretty neat and user friendly. This will help the search engines to index your pages correctly (now you can forget about rel=canonical) and will help in seo.
Now the reason for a trailing slash, consider a view (in any framework) which relatively resolves about.html for a user at path, users/awesomeUser
since users/awesomeUser and users/awesomeUser/ are different,
If the user is at users/awesomeUser, the browser will resolve it as users/about.html because there ain't a trailing slash which we don't want
If the user is at users/awesomeUser/, the browser will resolve it as users/awesomeUser/about.html because there is a trailing slash
child relative to family/parent/ is family/parent/child.
child relative to family/parent is family/child.
Django Design philosophy on Definitive URLs reads,
Technically, foo.com/bar and foo.com/bar/ are two different URLs, and search-engine robots (and some Web traffic-analyzing tools) would treat them as separate pages. Django should make an effort to “normalize” URLs so that search-engine robots don’t get confused.
This is the reasoning behind the APPEND_SLASH setting. (APPEND_SLASH lets you force append slashes to a URL)
Still not convinced?
Since django observes both the urls as different, if you are caching your app, Django will keep two copies for same page at user/awesomeUser and user/awesomeUser/.
You gotta have issues with HTTP methods other than GET if you don't append slash to a URL (If you ever plan to build a REST API).
Update
You can't make POST/PUT/PATCH/DELETE methods to work with rest_framework unless you explicitly define APPEND_SLASH=False in settings and trailing_slash=False for each and every router you gotta use(if you use Routers). It is like you basically gonna skip this most times and you gotta waste a hell lot of time debugging this. Django recommends append slashes and doesn't force it.
Its up to the developer to append slashes or not.
From the docs for the middleware that uses APPEND_SLASH
a search-engine indexer would treat them as separate URLs – so it’s best practice to normalize URLs.
Its not required by django, its just trying to help your SEO by suggesting a standard way of doing urls.
Yes, I know that the slash has nothing to do with this middleware but this is the best explanation I could find as to a possible reason
This helps define the structure of your website. Although django can support anything entered after the domain that is passed to the server doing it in this way allows you to easily add "subpages" to the url without it looking like accounts/loginreset?id=alkfjahgouasfjvn25jk1k25
That being said in the case above it may make sense to leave it out.
"URLs should be beautiful"!!!
I want to be able to control URLs. It's nothing nice when everything is about to be overwritten. Under circumstances, I make a redirect loop which is not funny.
from django.http import HttpResponseRedirect as rdrct
url(r'^sitemap.xml$', 'my_app.views.custom_sm'),
url(r'^sitemap.xml/$', lambda x: rdrct('/sitemap.xml')),

Want to learn django with REST without rest frameworks

I am a php programmer, I have built some REST based solutions in php. Now I am learning python/django. I want to make a REST based solution in Django ( only for knowledge purpose ). I do not want to use any of REST frameworks/toolkits as This project is more a exploring django/python say how they work with raw REST concept.
I searched on net, But examples/tutorial filled on already built solutions. I also checkout for request method based filtering. I am thinking of two approaches.
Either urls.py have way to check request method and transfer to respective method in views.py.
Or I can add a pre load hook/class which determine request method on application initialize, And called respective method so overriding urls.py behavior (my preferred method).
If anybody can suggest a django way to do this?
Update : I found some interesting comments on SO, like https://stackoverflow.com/a/20898410/1230744 AND https://stackoverflow.com/a/1732520/1230744. Need to check if they can have the solution, I am searching.
Well I get the answer of my questions finally from following link. It is possible through using Class based Views + serialization.
Restful routes and Django
Snippet links in side above link gave pretty much example to gave quite picture of how one can create a REST Api using only Django Core. Also I used serialize https://docs.djangoproject.com/en/dev/topics/serialization/ for Json encoding
( Now if anybody prefer, he can flag duplicate the question. ;) )
You can start from learning the code of this projects:
http://tastypieapi.org/ Tastypie
http://www.django-rest-framework.org/ Django REST framework
They are snadrd de facto for REST API for Django and their code could be a good starting point.
Also, please review this questions:
Creating a REST API for a Django application
Adding REST to Django
Django and Restful APIs

How to check user agent inside Django template?

I want to check the useragent using Django inside my template. I know this is possible using JavaScript, but I wanted a server side solution.
I know I can use HttpRequest.META in some middleware class, which I am not currently looking for. I want to determine this using some code in the template itself, without any dependency on other files / classes.
Can anybody help?
You need to use context processors, more specifically django.core.context_processors.request.
This SO answer covers it quiet well:
How can I pass data to any template from any view in Django?
Especially this blog post, that is referenced in the SO answer:
http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/

Django admin site: implement a singleton for global variables?

Does anyone have experience (Django 1.x pref 1.3) with implementing a sort of singleton accessible from the admin page to expose some global variables for editing (site name, keywords, ...).
I cant find anything like this and it sounds quite unbelievable!
thanks
(django-preferences is broken with 1.x)
As lazerscience says, you probably want Django-dbsettings. I have a fork at Github that works with the latest Django versions.
after some playing I had dbsettings working... but with a few glitches:
- Aptana doesnt recognise the import preferences as a valid reference
- when I access my /settings/ page with the fields of the model I created and then save it I have a CSRF token missing or incorrect. error
NOTE: The official googlecode repository doesnt work (with 1.3), Daniel's version does instead (I guess he changed newforms -> forms etc). The way I created a new model for the settings veiw is:
from django.db import models
import dbsettings
class ImageLimits(dbsettings.Group):
maximum_width = dbsettings.PositiveIntegerValue()
maximum_height = dbsettings.PositiveIntegerValue()
options = ImageLimits()
You should avoid using singleton's as much as possible.
Are Singletons really that bad?
What is so bad about singletons?
For the rest, site name is editable in Django admin (see django.contrib.sites module).
Talking about keywords - it's bad to repeat them, thus, you better implement it in your item model (page, news article, etc).
Could you maybe give more examples of what do you need it for?

Categories

Resources