How to change the url in urls.py? (Django app) - python

I'm trying to change the url of http://localhost:8000/stories-and-literature/fairy-tales/ to http://localhost:8000/stories-and-literature/classic-literature/, and I'm not to sure how I can change it in my urls.py. So far, I have this code in urls.py:
from django.conf.urls import patterns, url
from topictree import views
urlpatterns = patterns('',
(r'^$', 'topictree.views.index'),
(r'^(?P<slug>\D+)/$', 'topictree.views.tree')
)
I want to change the slug of url from "fairy-tales" to "classic-literature" because I want to present the url like a tree. In this case, both "fairy-tales" and "classic-literature" are children of "story-and-literature", so when I click on the "fairy-tales" link and then click on the "classic-literature" link, the "fairy-tales" slug should be removed, and be replaced by the "classic-literature" slug.
I was thinking of changing the url in views.py instead of urls.py since views.py contains the control flow of the program. Is it possible to change the url in views.py instead of urls.py?
Any help would be much appreciated.

Foo Bar User's link is a good place to start but judging by your question I would say you should go straight to the Django Docs
https://docs.djangoproject.com/en/1.6/topics/http/urls/
That should get you back on your feet. :)

Related

URL Regular Expression mismatch

I am trying to learn Django and I am currently stuck in an issue.
I created an app Contact and run the server, I get the error.
The error page displayed by server:
The urls.py file in the app Contact
urls.py in conatct
When the pattern in urls.py is
urlpatterns =[url(r'^$', views.form, name ='form')]
it works properly, but not with other pattern shown in the picture
Your help would be greatly appreciated.
The Page not found error message tells you what went wrong: For the URL (/contact) you requested, Django was unable to find a suitable view. Because you have debugging enabled, you get some information, including a list of registered views.
First things first: You probably have url(r'^contact/', include('contact.urls')) somewhere in your top level urls.py. This makes the URLs defined in the contact/urls.py available under the prefix /contact.
With
urlpatterns = [
url(r'^form/', views.form, name='form'),
]
in contact/urls.py you are telling Django that you want urls starting with contact/form/ to be handled by views.form.
Consequently, when you access http://localhost:8000/contact/ in your browser, there is no view associated with that URL, hence the 404. Your view is reacting to to http://localhost:8000/contact/form, not http://localhost:8000/contact.
When you change the URL pattern to
urlpatterns = [
url(r'^$', views.form, name='form'),
]
you modify the URL views.form reacts to.

Django redirect based on parts of url pattern

So I have this small simple problem that I can't really find a solution to.
I would like to redirect all links on the form r'^blogg/ to r'^blog/'. I would think there is a solution similar to the accepted answer in this post here, but it doesn't work that well. Note that the blog-application has many sub-url-patterns, so a solution like RedirectView.as_view(url="/blog/") would not work.
In my main urls.py
urlpatterns = patterns('',
url(r'^blogg/', RedirectView.as_view(pattern_name="blog")),
url(r'^blog/', include("blog.urls", namespace="blog")),
The solution above returns HTTP 410 (Gone) for all sub-urls of blogg. I suspect this is due to the missing url argument in RedirectView.as_view().
Thanks in advance for all answers!
You won't be able to do this entirely in urls.py. But a simple view function could work:
url(r'^blogg/(?P<rest>.+)$', views.redirect_prefix),
from django.shortcuts import redirect
def redirect_prefix(request, rest):
return redirect('/blog/{}'.format(rest))
What about
urlpatterns = patterns('',
url(r'^blogg/',include("blog.urls", namespace="ignoreme") ),
url(r'^blog/', include("blog.urls", namespace="blog")),
it both should strip the first part (blog/ or blogg/) from url and then manage the rest equally. And if you will use {% url "blog:this_view" %} then on next page your customer will be on the blog/ part anyway

Django media page not found 404

I'm trying to learn to work with Django and i'm making a image app.
Now I managed to upload images to my database, but now I want to retrieve them.
The images are stored in media/images/.
Now I made an admin page that looks like this:
AS you can see the thumbnails don't load.
When You click on one of those thumbnails, I get the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/images/june.png
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, media/images/june.png, didn't match any of these.
Here is my urls.py of my main thinghy (not the app, wich is called photo):
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Now I'm not sure what I exactly need to do to fix this.
I hope you can help me.
Please be clear ( small steps ) cause I'm not that experienced with django.
Thanks in advance
Oh BTW i'm on Win7
EDIT:
this is what I added to my settings/py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/http://127.0.0.1:8000/media/'
So right now, your urls.py doesn't have a pattern for /media/images. That pattern probably exists somewhere in your photo app. You need to link the urls for your photo app into your primary urls.py, something like:
url(r'^media/', include('photo.urls')),
This would tell the app that if it sees a url with media/ it should look for the next thing ('images/') in the photo app.

Can't find page in django

I'm currently learning Django and I'm trying to add form to register a User.
Now my problem starts really early because I get a 404 whenever I try to access my registration page.
My 3 files are as follows:
views.py : just a hello world to display basically
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello World")
def registration(request):
return HttpResponse("Registration page")
urls.py (in my project) :
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
(r'^$', include('myapp.urls')), # index with login/registration
(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
(r'^admin/', include(admin.site.urls)), # admin site
)
and finally urls.py (in my app) :
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^$',views.index, name='index'),
url(r'^registration/$',views.registration, name='registration'),
)
When I go to my normal index (localhost:8000) It displays the hello world I wrote in the views.py file. However when I try to go the registration page it just returns me a 404 (localhost:8000/registration).
Now as I said I'm still learning this whole thing, but I don't get why It doesn't work properly. As far as i understand the r'^$' in the project file is pointing towards the localhost:8000 and the same regex in the app file tells it to load the index page in this location. Now as the program is still in localhost:8000, a r'^registration/' should be loading the other page in localhost:8000/registration right?
It would be really nice if you could explain to me why this doesn't work and where I did a mistake in my thoughts.
This is the error I get:
When i take
(r'^randomstringhere/', include('myapp.urls')), # index with login/registration
instead of
(r'^$', include('myapp.urls')), # index with login/registration
I can get to the registration page via localhost:8000/randomstringhere/registration. But Site is meant to have a selection where you can either Log in or register on localhost:8000 (or future domain www.randomdomainhere.com) and a registration/login form on localhost:8000/login, localhost:8000/registration (www.randomdomainhere.com/registration etc.)
At the end of each url you should add a $ symbol,
url(r'^registration/$',views.registration, name='registration'),
reffer this https://docs.djangoproject.com/en/1.4/topics/http/urls/
you are missing $ sign in the end of url.
It should be:
url(r'^registration/$',views.registration, name='registration'),
The $ symbol in django urls means end-of-string match character which is borrowed from regular expression. So, $ should be added at the end of your url on app's urls.
url(r'^registration/$',views.registration, name='registration'),
However we can write urls with the regular expressions that don’t have a $ (end-of-string match character) but we do have to include a trailing slash(/). For urls without $, you must enter the trailing slash while opening the url in your browser to match the regular expression.
Your app urls in project's urls.py is
url(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
So, to access the registration page, you need to browse by
localhost:8000/grappelli/registration/
i.e. append the path in your app's url to the path in project's url for the app.
Learn more about urls here.
You need to remove $ from the first url as given below
urls.py (in my project) :
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
(r'^', include('myapp.urls')), # index with login/registration
(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
(r'^admin/', include(admin.site.urls)), # admin site
)
A url starts with ^ and ends with $. so if $ is encountered django understands that the url has ended and there's nothing more infront of that. so in your case it will no more look for "registration". or if your url with "registration" doesnt matches to any urls specified at all.

Multiple django apps using same url pattern

I'd like to run two apps with the same url patterns. I would like to avoid having an app-specific slug like domain.com/pages/something-here or domain.com/blog/something-there.
I tried this:
# urls.py
urlpatterns = patterns('',
url(r'^$', 'my.homepage.view'),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('pages.urls')),
url(r'^', include('blog.urls')),
)
# pages/urls.py
urlpatterns = patterns('',
url(r'^(.+)/$', views.page),
)
# blog/urls.py
urlpatterns = patterns('',
url(r'^(.+)/$', views.post),
)
My code doesn't work, whichever include comes first (here, pages.urls) works ok, other urls (for blog) throw 404.
Thanks in advance
EDIT: I did it like this: created glue.py in the same directory as settings.py. It will handle my homepage and this dispatcher view:
def dispatcher(request, slug):
try:
page = get_object_or_404(Page, slug=slug)
return render(request, 'pages/page.html', {'page': page})
except:
post = get_object_or_404(Post, slug=slug)
return render(request, 'blog/post.html', {'post': post})
I don't know if it's ok. I hope there is a better way.
Thanks for the comments.
I don't know if this is a better answer. But, if these situations are satisfied for you..
if your django app is based on django template rendering.
The url you are talking about, need not be accessed directly by typing the endpoint in the browser itself.
Then, maybe you could consider url namespaces and template redirections.
https://docs.djangoproject.com/en/1.11/topics/http/urls/#url-namespaces
This doesn't work because django urls are resolved in order, meaning that the first url that matches the regexp will be the resolved one. In your case, the the urls included from the blogs application will never be searched, as django already resolved the url on the pages includes line.
Also, the django url module is not supposed to know if a certain page or blog post exists, as i believe in your application this is determined with a database lookup.
The urls module just executes the view that is connected to the first regexp that matches.
You should change your logic, e.g. with perpending "blog/" to blog urls (what's wrong with that?)
url(r'^blog/', include('blog.urls')),
url(r'^', include('pages.urls')),
Notice that the i moved the blog url up, as most generic regxexp should always be the last to be tried by django url resolver.
Alternatively, you could code a proxy view that tries both blog posts and pages. but it doesn't seem the best way to do it to me.
How would you like this to work? They're both using the same URL (which of course is causing problems). How would a user get to a "page" rather than a "blog" or vice versa?
In general, you can't have overlapping URLs in your URL patterns (without including additional data).
EDIT:
So you want the first app to check if it has a view to match the URL and next to take over if the first doesn't? You could do something complicated like writing a "view matcher" to do want you want, but there are much more straigtforward solutions.
The easiest way would be to alter the slug generation function for one of your apps. Have one use some delimeter other than underscores, or always append the name of the app to the slug. This way you could find pages because their url would be "some-slug-page" and blogs would be "some-slug-blog", which you could then write a URL pattern for. If you don't want to add the entire URL, you can append/prepend just the first letter, or whatever you want.
Just think about a way that's acceptable to you to generate URLs for each app which, just by reading the URL, lets you know which app the page belongs to.

Categories

Resources