Django URLConf for former forum URL - django

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.

Related

Use anchored urls in django (anchored by the id of http objects)

My level in front-end development is pretty low.
Nevertheless, I want to implement the very wide-spread behaviour of having several parts anchored in one single page instead of several separate pages, and refer to these parts in the url.
So instead of having mysite.com/how_to_walk and mysite.com/how_to_run as two different pages and templates, I would like to have one page mysite.com/how_to_do_stuff and then depending on if you want to #walk or #run, refer to the html headers with the id field as suffixes of the url.
I don't really know how to do it with django. I'd like to create only one url dispatcher that - I guess - will look like that:
url(r'^how_to_stuff/#(?P<partId>[-\w]*)', views.how_to, name='how_to')
...and then I have to create a simple view, but how to refer to the id in the render() call, I have no idea.
I found the answer to my own question. The crucial element is that when the client (browser) goes for such an anchored url mysite.com/how_to_do_stuff#run, it sends to the server only the root url mysite.com/how_to_do_stuff and then applies the anchor to it locally. So you need:
A classic, simple url/view/template combination that loads the page mysite.com/how_to_do_stuff when it is asked by the client.
A way to send the client to these anchored pages and reference them for development. I do this through an other url/view couple that redirects the client to the right anchored url.
Below is the result:
In urls.py:
...
url(r'^how_to_do_stuff/(?P<part_id>[-\w]+)', views.how_to_redirect, name='how_to'),
url(r'^how_to_do_stuff', views.how_to)
In views.py:
def how_to_redirect(request, part_id):
return HttpResponseRedirect("/how_to_do_stuff/#"+part_id)
def how_to(request):
return render(request, "GWSite/how_to_do_stuff.html")
And then I refer to these in my templates through:
{% url "how_to" "run"}
From django project website
Take a look at how you they send the num var to views.py
# URLconf
from django.conf.urls import url
urlpatterns = [
url(r'^blog/$', 'blog.views.page'),
url(r'^blog/page(?P<num>[0-9]+)/$', 'blog.views.page'),
]
# View (in blog/views.py)
def page(request, num="1"):
# Output the appropriate page of blog entries, according to num.
...

django url parse formatted url

I'm in the design stages of a single page web app, and would like to make it so that a user can click on a formatted URL and the data requests will load in the page.
For example, a url of http://www.mysite.com/?category=some_cat will trigger the Category view with the relevant data.
My intention is to parse the URL, gather the data, then pass it to the index.html template for rendering on page load. Once the page has been loaded, a Javascript trigger setting will trigger the appropriate button to load the client view.
However, I'm having an issue setting up the URL parser, as the following settings are not matching the example url above.
from app.views import app_views, photo_views, user_views, admin_views
urlpatterns = patterns("",
url(r'^/(?P<category>\d+)/$', app_views.index)
)
You're confusing between sending information through your urls with GET and formatting you urls with arguments for the view functions. Say I am visiting a site called http://www.mysite.com/ and the page has a form that looks like this:
<form>
<input type='text' name='category' id='category'></input>
<button type='submit'>Send!</button>
</form>
upon clicking, the url will automatically change to http://www.mysite.com/?category=<value of input>. The ? marks that everything afterwards should be treated as GET data, with the syntax of <id>=<value>. You can then access them like so:
def response(request):
category = request.GET['category']
formatting urls is different, because it means looking for patterns that are part of the url. i.e. a pattern that looks like r'^/(?P<category>\d+)/$' will look for this: http://www.mysite.com/<category>/ and it will send it to the request in your views as an additional argument like so:
def response(request, category):
...
The regex is used to define how you recognize that part of the url. For example, the \d+ you're using means that category needs to be a number. You can search how to define different types of patterns according to your needs
Note that with GET you are sending the data to the same view function that rendered the page you are currently visiting, while using a different url means you tell it where to go through your urls.py (usually a different function). Does that make things a bit clearer?

How to organize URLs in django for views handling GET data and parsing URL?

I have a view that displays some movie data. I thought that it might be a good idea to have a view handle a an URL like movie-id/1234 to search for movie id 1234. Furthermore I would like to be able to enter the ID into a form and send that to a server and search for it. To do that I created a second entry in the urls.py file shown below.
urlpatterns = patterns('',
url(r'movie-id/(?P<movie_id>.+?)/$', 'movieMan.views.detailMovie'),
url(r'movie-id/$', 'movieMan.views.detailMovie', name='movieMan.detailMovie.post'),
)
So if I want to pass data to my view either via a URL or a GET or POST request I have to enter two urls or is there a more elegant way? In the view's code I am then checking if there is any GET data in the incoming request.
To make the second url usable with the template engine, where I wanted to specify the view's url using the {% url movieMan.detailMovie.post %} syntax I had to introduce a name attribute on this url to distinguish between these two.
I am not sure if I am thinking too complicated here. I am now asking myself what is the first url entry good for? Is there a way to get the URL of a movie directly? When do these kinds of URLs come into play and how would they be generated in the template ?
Furthermore I would like to be able to enter the ID into a form and
send that to a server and search for it.
Is this actually a search? Because if you know the ID, and the ID is a part of the URL, you could just have a textbox where the user can write in the ID, and you do a redirect with javascript to the 'correct' URL. If the ID doesn't exist, the view should return a Http404.
If you mean an actual search, i.e. the user submitting a query string, you'll need some kind of list/result view, in which case you'll be generating all the links to the specific results, which you will be sure are correct.
I don't think there is a more elegant way.
I did almost the same thing:
url( r'^movies/search/((?P<query_string>[^/]+)/)?$', 'mediadb.views.search_movies' ),
The url pattern matches urls with or without a search parameter.
In the view-function, you will have to check whether the parameter was defined in the url or in the query string.

Validating URL slugs

I'm creating an app in which many urls are using a pattern like /foo/bar/<object_id>/<object_name_slug>/, like many applications (SO included), which is itself a straightforward pattern to implement. However, I don't want to just blindly ignore the contents of the slug field and open the app up to stupid stuff like people distributing a doctored URL (e.g. the recently popular http://www.independent.co.uk/life-style/food-and-drink/utter-PR-fiction-but-people-love-this-shit-so-fuck-it-lets-just-print-it-2269573.html).
My plan is to validate the slug an issue a redirect to the correct URL if someone reaches a page via a bad slug (again, like SO). This would be trivial to implement in the view, but since this will be a pattern used on many views, I'd like to factor it out into something reusable--probably a decorator or a middleware.
What's the best way to do this? Could a decorator determine which url pattern was matched by a particular request so that it could generate a reverse if necessary?
Thanks for the ideas.
You could use middleware for this. Cross-check the Entry id (let's just suppose you use the Entry model for content. The ID in the URL you mention would be 2269573 for example) with its slug (supposing your Entry model has a slug field of course). If the slug is incorrect, just redirect to the correct page.
In order to do this, create a class, and give it the process_request method. Then add this class to your settings' MIDDLEWARE_CLASSES.
The process_request takes a "request" parameter (a HttpRequest object), and this object has a path attribute that will give you the URL that was requested.
Based on that URL you can define the actions to be undertaken.
The method of your middleware class should return None or a HttpRequest object. The latter can be a django.http.HttpResponseRedirect instance, meaning you can redirect to the correct URL (thereby ignoring the incorrect slug).

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.