django url parse formatted url - django

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?

Related

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.

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.
...

How do I access my query when using Haystack/Elasticsearch?

I originally followed this tutorial (https://django-haystack.readthedocs.org/en/latest/tutorial.html), and have so far been able to highlight my query within my returned results. However, I want to highlight this same query when visiting the next page that I load with a separate template. Is there any way to save/access this query so that I can highlight the same results within this other template?
Whenever I try and include a statement like this, I get an error, which I'm thinking is because I'm not trying to access the query properly.
{% highlight section.body with query html_tag "span" css_class "highlighted" %}
You have to send to the next page, the information that you use to highlight the results in the first page. You can use the request.session to store the data and call it in the next page, or you can send the sqs by the url to the next page.
If you want to know how to manage the search query set, and how to edit that kind of stuff, I recommend you to read the views.py forms.py and the elasticsearch_backend in the haystack folder at: "/usr/local/lib/python2.7/dist-packages/haystack"
This is the url for the documentation of Django Session: Django Session
This is the url for the documentation to pass parameters trhough url: URL dispatcher

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.

View referenced by two urls and url tag

I am using url tag in my template for a view, that is used by two different urls. I am getting the wrong url in one place. Is there any way to force django to retrieve different url? Why it doesn't notify my, that such conflict occured and it doesn't know what to do (since python zen says, that is should refuse temptation to guess).
Code in template:
{% url djangoldap.views.FilterEntriesResponse Entry=entry.path as filter_url %}
Code in urls:
(r'^filter_entries/(?P<Entry>.*)/$',
'djangoldap.views.FilterEntriesResponse',
{'filter_template': 'filter_entries.html',
'results_template': 'filter_results.html'}),
(r'^choose_entries/(?P<Entry>.*)/$',
'djangoldap.views.FilterEntriesResponse',
{'filter_template': 'search_entries.html',
'results_template': 'search_results.html'}),
As you can see, those two urls use the same view, but with different templates. How I can force django to retrieve former url, rather than latter?
Name your URLs by adding another item to the tuple:
(r'^choose_entries/(?P<Entry>.*)/$',
'djangoldap.views.FilterEntriesResponse',
{'filter_template': 'search_entries.html',
'results_template': 'search_results.html'},
'sensibleprefix-choose_entries') # <-- this is the name
Then you can use the name in the URL tag.