Urlpatterns: category/subcategory/article-slug - django

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

Related

the current path ,About.html didn't match any of these in django

from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^$', views.index,name='index'),
url(r'^About/', views.About,name='About'),
url(r'^checkout/', views.checkout,name='checkout'),
url(r'^contact', views.contact,name='contact'),
url(r'^faqs', views.faqs,name='faqs'),
url(r'^help', views.help,name='help'),
url(r'^icons', views.icons,name='icons'),
url(r'^payment', views.payment,name='payment'),
url(r'^privacy', views.privacy,name='privacy'),
]
The error message:
Page not found (404)
Request Method:
GET
Request URL:
http://127.0.0.1:8000/About.html
Using the URLconf defined in shop.urls, Django tried these URL patterns,
in this order:
admin/
^$ [name='index']
^about/$ [name='about']
^checkout/$ [name='checkout']
^contact/$ [name='contact']
^static\/(?P<path>.*)$
The current path, About.html, didn't match any of these.
This kind of an error could occur from 2 or 3 different scenarios.
In your case, you seem to put the wrong URL in the browser address bar.
Your correct URL should be http://127.0.0.1:8000/About (as you've written in the URL patterns).
Remember, About.html - is the HTML template you create inside the templates folder. Even though you route to the html page (with a string like: app_name/About.html) - the actual URL in the address bar will be according to what you write in the regex path r'^url_name'. If you write r'^About.html' in url patterns, then http://127.0.0.1:8000/About.html should work perfectly.
The second scenario (based on my experience) which could produce this type of an error is when you forget to pass the 'request' argument inside the method that defines view of the URL - in the respective views.py file.
You should be having a method named About which would look like this in views.py
def About(request):
return render(request,'app_name/About.html')
If you forget to pass argument in the paranthesis of About, this kind of an error could occur.
Finally, if you are using django 2, please start using re_path method to serve regex url patterns. The url method is likely to be depracated in future release.
Refer re_path documentation.
your URL will not be http://127.0.0.1:8000/About.html it will just be http://127.0.0.1:8000/about (remember urls are case insensitive), this will take you to your view which is named About, in your view you should reference your template in its render (about.html)
have you read the my first Django app https://docs.djangoproject.com/en/2.0/intro/tutorial01/ its a great place to start if you are unfamiliar with how django operates
What you are trying to hit is not a valid url, you have to hit http://127.0.0.1:8000/About as written in urls.py.
You have to understand the difference between urls and html templates, this About.html would be used in views while rendering like:
return render(request, 'your_app/about.html')
And for sure you can write a url if you want like this:
urlpatterns = [
url(r'^$', views.index,name='index'),
url(r'^About.html/', views.About,name='About'),
.
.
]
Check the documentation
The url which you provide in url ( ) method doesn't contain any suffix of .html
You can goto the about page directly by /About

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 urlconf sometimes failing?

I've got a django urls.py file like so:
Base file:
urlpatterns = patterns('',
(r'^', include('sp.sp_app.urls')),
(r'^', include('sp.sp_api_activity.urls')),
(r'^', include('sp.sp_api_player.urls')),
(r'^', include('sp.sp_web.urls')),
)
In the sp.sp_web.urls file, I have the following:
from django.conf.urls.defaults import *
urlpatterns = patterns('superproof.superproof_web.views',
(r'^$','index'), #Shows your home page
(r'^challenge$','spcreatechallenge'),
(r'^player/`$','getlastactivity'),
(r'^yearlysummary/','yearlysummary'),
(r'^processchallenge$','processchallenge'),
(r'^activity/(\w{32})$','activitydetail'),
)
The yearlysummary url is loading sometimes. Other times, I get a 404 error. This happens with the exact same valid URL. I don't change anything in the URL, or in the code.
When I get the 404 error with debug turned on, my yearlysummary URL pattern isn't on the list.
Any ideas?
A couple things I noticed that could be an issue...
I notice you are not namespacing your included urls for each app. Not knowing what the other urls modules look like, I can assume its possible that you can have colliding urls. I Would recommend doing something like this:
urlpatterns = patterns('',
(r'', include('sp.sp_app.urls')),
(r'^activity/', include('sp.sp_api_activity.urls')),
(r'^player/', include('sp.sp_api_player.urls')),
(r'^web/', include('sp.sp_web.urls')),
)
Normally when you have url includes, they are for different apps, so you would want to namespace them to avoid two apps specifying the same url pattern.
Also, whats that back-tick in one of your urls? Did you mean to expect that?
(r'^player/`$','getlastactivity'),
jdi is spot on, on the analysis. I'll try to explain why exactly is there the issue, in your case.
You will notice that if you include (r'^', include('sp.sp_web.urls') as the first pattern in the main urls.py, your view will rightly load always.
When you have it as the last pattern, the reason it doesn't match the other times is that, that pattern is matching some other pattern in the earlier pattern, say [/w+]. The debug page, on a 404 of the url pattern, displays all the sub-url patterns of one of the patterns it matches. This is exactly why the pattern isn't on the urls displayed on the debug page.
Like jdi mentions it is a good practice to namespace the urls properly, so this doesn't occur. You can probably do it even without namespacing, but your regexes have to be proper, with the end character $ included, at least.

Regex Url conf Django

I am trying to get the following setup up going.
Flatpages: Where all my static sites are (like: about, contact,..)
Dynamic Pages:
Here I am trying to link from one of the Flatpages to a start site:
the regex in the url conf of this startsite I tried was:
(r'^myapp/start/(\d+)/$', 'mysite.views.def_that_should_just_show_hello_world'),
In the views I had:
def def_that_should_just_show_hello_world(request):
return HttpResponse("Hello experiment world")
If I go to
/myapp/ I get 404: No FlatPage matches the given query.
/myapp/start/ I get 404: No FlatPage matches the given query.
/myapp/start/1 I get
Exception Type: TypeError
def_that_should_just_show_hello_world takes exactly 1 argument (2 given)
I thought with this setup I would get "Hello experiment world" on EVERY page.
Where did I go wrong?
I dont understand the multiple sites approach in regexs.
What would I have to do to print hello world on all these sites?
And then, what would I have to do to display 1 image on all of these sites?
Thanks a lot for the help!
You regular expression has a matching group in it - the (\d+) bit.
This requires one or more numeric characters to appear at the end of the url for that view. If you do not include the number at the end, this regular expression will not match the url. (url matching works like any other regular expression matching).
When you do include the number, eg. /myapp/start/1 you then have another problem. Because there is a matching group, the part of the url in the brackets will be passed as another argument to your view. Views are always passed the request as their first parameter but in this case the '1' matched by the (\d+) is provided as a second argument. This is why you are hetting the TypeError in this case.
Django's documentation has a lot of information on how url dispatching works, read that through and see if that makes sense!
from your_app_name import views
from django.conf.urls import url
urlpatterns = [
url(r'^$',views.method_name,name ='index'),
path('admin/', admin.site.urls),

URL Patterns in Django - Different Combinations

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.