To access the details page of an Item on my site, one would use the following url
<mydomain>/item/1
where 1
is the primary key of the Item
I am looking for a solution that allows me to redesign the url with the following requirements:
I intended to ask this as a general web design question, but just thought I should mention that I am working with Python/Django.
To do so, use re_path() instead of path() . In Python regular expressions, the syntax for named regular expression groups is (?P<name>pattern) , where name is the name of the group and pattern is some pattern to match.
Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL.
A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs."
Set up app folder's urls.py and html files In the same directory, you should have a file named views.py. We will create a function called index which is what makes the http request for our website to be loaded. Now, we've set it up such that http://127.0.0.1:8000/homepage will render the HTML template index.
You need to have some kind of identifier in the URL, and this identifier:
so there aren't all that many options, and the object's primary key is the best choice. If for some reason you can't use that (why not?) you can encode or obfuscate it: see this question and its answers for some ideas about how to do that.
Stack Overflow's own URL design is worth a look. You can reach this question via any URL of the form
https://stackoverflow.com/questions/9897050/any-text-you-like-here!
This allows the URL to contain keywords from the question's title (for search engines) while also being able to change when the title changes without breaking old links.
I don't like the slugfield option because it adds an additional query to the database.
I did the following in a project:
My URL looks like this:
<domain>/item/5927/728e26e9464a171b228bc9884ba3e4f76e2f8866/
This is:
<domain>/item/<id>/<hash>/
If you don't know the hash you can't get to the item:
urls.py:
url(r'^item/(?P<id>\d+)/(?P<hash>\w+)/$', 'rwapp.views.item', name='item')
views.py:
from hashlib import sha1
def item(request,id=None,hash=None):
if not id:
return HttpResponseRedirect("/home")
if hash:
chash = sha1("secret_word%s"%id).hexdigest()
if not chash==hash:
return HttpResponseRedirect("/home")
else:
return HttpResponseRedirect("/home")
Of course, every time you render the URL you have to add the // part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With