URL Patterns in Django - Different Combinations - django

I'm finding it hard to understand what exactly is passed to the patterns method in Django.
You see, I usually have my urls.py as:
urlspatterns = patterns('example.views',
(r'/$','func_to_call'),
)
Then in func_to_call I would get everything I want from the request object by using request.path. However on a second take, it's really quite horrific that I'm ignoring Django's slickness for such a longer, less clean way of parsing - the reason being I don't understand what to do!
Let's say you have 3 servers you're putting your Django application on, all of which have a domain name and some variation like server1/djangoApplicationName/queryparams, server2/application/djangoApplicationName and server3/queryparams. What will the urlpattern get passed? The whole url? Everything after the domain name?

The URLconf regex sees only the path portion of the URL, with the initial forward-slash stripped. Query parameters are not matched by the URLconf, you access those via request.GET in your view. So you might write a pattern like this:
urlpatterns = patterns('myapp.views',
url(r'^myapp/something/$', 'something_view_func')
)
The documentation has more examples and details.

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"),

Django URLConf for former forum URL

I am tryimg to add content to a URL previously served by forum software. The URL is
/portal/forums/showthread.php?t=12345
I have this in my urlconf, but it's not working:
url("^portal/forums/showthread.php?t=12345", thread),
I am just matching the whole string to a single view for now, but a way to pass the topic ID as an argument would also be handy. (Hopefully all the old URLs similar enough to match, without any funky querystrings)
You need to access GET (Query string) parameters like this:
def myview(request):
t = request.GET.get('t')
#rest of the code.
The GET parameters should not be a part of the URL.
Your URL then would look like this:
url("^portal/forums/showthread.php", thread), #You might want the $ sign at the end.

Django-CMS AppHooks with conflicting urls?

I'm trying to use django-cms app hooks in a different way. I have only an app, with different website pages. For each page, i created an AppHook, since i want to have control of all of them with the cms.
To do that, inside the app, i did a package, with urls.py file for each of the page, example:
/urls
/home_urls.py
/portfolio_urls.py
/contacts_urls.py
Here are the definition of some app hooks:
class WebsiteHome(CMSApp):
name = _("cms-home")
urls = ["website.urls.home_urls"]
apphook_pool.register(WebsiteHome)
class WebsiteServices(CMSApp):
name = _("cms-services")
urls = ["website.urls.services_urls"]
apphook_pool.register(WebsiteServices)
Anyway, the problem is: i don't have any control on the regular expressions. Each one, is entering on the first regular expression that it founds, in this case, the urlpattern in the
website.urls.home_urls
Despite, having different apphHooks.
Example:
if i write a slug contacts (that has an apphook to WebsiteContacts), it still goes to the home_urls.py file, associated with the WebsiteHome (app hook).
Did anyone had a similiar problem?
Basically, what I'm trying to say is that it's something wrong with the regular expression. I can't make:
url(r'^$', [...]),
only:
url(r'^', [...]),
If I put the '$', it doesn't enter on any regex. If I take it, it enters always on the
website.urls.home_urls.py
Despite the slugs having different Apphooks, associated with different urls.py files.
Have you tried r'^/$'? I'm using r'^/?$' in some app-hook urls, but I wonder if r'^$' is failing for you because of a '/'?
As you've defined each of those URL files as individual app hooks in CMS then they'll each get attached to a certain page in the CMS e.g.
www.mysite.com/home
www.mysite.com/contacts
www.mysite.com/services
etc
Because those URL files are attached to pages this should prevent conflict between urlpatterns. For example, I've got an URLs file attached to a CMS app called News which looks like this;
urlpatterns = patterns(
'',
url(r'^(?P<slug>[-_\w]+)/$', NewsDetailView.as_view(), name='news_detail'),
url(r'^$', NewsListView.as_view(), name='news_list'),
)
Which is attached to a page at mysite.com/news so if I go to mysite.com/news/myslug I hit that NewsDetailView and if I go to mysite.com/news I hit NewListView.
Using this example, if you had a slug for a contact you'd go to mysite.com/contacts/contact-slug to hit that NewsDetailView.
And just a sidenote on the urlpatterns in case you're not aware, the ^ in the regex signifies the start of a pattern to match, and the $ signifies the end. URL dispatcher docs

django urlpatterns from sql

I am trying to create urlpatterns with sql query, but this will work only for those things that already was in sql table at the moment of server start. If it possible to make django to check for new urls dynamically from database?
I know, this can be done with regular expressions, but they are too greedy, I mean, that i need to make this at root level of my site and regexp will "eat" all matching names and this regexp must be the last of urlpatterns list.
Going on your comment to pyeleven's answer, it seems you have understood the point of urlpatterns. You don't need or want to specify the choices of your section in the urlconf. What you do is grab the value of each section of the url, and pass that as a parameter to the view. So, for example:
(r'^?P<section>\w+)/$', 'my_view')
This will grab urls like /name1/ and /name2/, and pass name1 and name2 to the view as the section parameter. So there's no need to change the code whenever you add a section.
Although this is the nastiest, most un-django-esque thing imaginable, you can get your urls from the db, if you really, really want to:
models.py:
from django.db import models
class Url(models.Model):
name = models.CharField(max_length=20)
urls.py:
from my_app.models import Url
urls = []
for url_object in Url.objects.all():
urls.append(url(url_object.name, 'my_view'))
urlpatterns = patterns('my_app.views', *urls)
Voilà. It actually works. Url patterns directly from the db. Please don't do this.
I'm going to go take a shower now.
Have you checked django flatpages?
http://docs.djangoproject.com/en/dev/ref/contrib/flatpages/?from=olddocs
Dynamic url might not be such a good idea, for example a bad url line added dynamically might make the server stop functioning.
Can you elaborate on your goals?

Django url configuration for DRYness

Most views in my project accept an optional username parameter and if exists, filter the querysets passed to the templates for that user. So, for example:
the index view handles both the following url patterns:
'^$' # general index page
'^(?P<username>[-\w]+)/$' # index page for the user
'^photos/$' # photo index page
'^(?P<username>[-\w]+)/photos/$' # photos for that user
...
As there are a number of such applications, it doesn't seem very DRY to implement the same logic by replicating the patterns. I thought it may be possible to recursively include the main urls.py module, so I did this:
url(r'^(?P<username>[-\w]+)/', include('urls')),
My reasoning was that, when an other urls module is included, the matched pattern is removed from the path. So, I was hoping that
'^(?P<username>[-\w]+)/photos/$'
would become
'^photos/$'
when it is matched by the recursively included urls module, with the extra username parameter. But this caused the development server to die silently when a request is made.
The second approach I can think of is to write a middleware, which would match the pattern in the url, if exists, and add the viewed user to the request and remove the part that matches the username from the request path. But I don't want to mess with the path as this may have unpredictable results.
What would you recommend? Am I too picky for DRYness?
Thanks,
oMat
Just define the regex as a string in the same file and use the string concatenation already!
user_regex = r"^(?P<username>[-\w]+)/"
Then you can do regex '%s/photos$'%user_regex so that you keep the regex defined only once, very dry.
Altho', your reasoning for including the urls.py patterns within the url tag is right and I'm not sure why it failed. Perhaps some other error?