Django urls.py, what does the name parameter do? - python

I was poking around my friends project and as I looked through the urls.py file i noticed this:
url(r'^apply/$', contact.as_view(), name='careers_contact'),
I just recently learned about class based views, and it all makes sense to me except for the last bit name='careers_contact'. I also can't seem to find the meaning of this online.
Can someone shed light on what this is, where that name lives, and what its doing?

url() name parameter
"What is it? Where does it live?"
url() is simply a function that returns a django.core.urlresolvers.RegexURLPattern object, so passing in a name='careers_contact' argument sets name for that object. None of that is really relevant until this url(...) is placed into a URLconf.
THEN, if we need the URL of a view, we can now get it by passing that name into {% url 'careers_contact' %} in templates or reverse('careers_contact') in code and on the backend those functions will use the name to map back to the correct URL.
Why do we need it?
We can reverse the Python Path to get the URL (ex. reverse(blog.views.home) ), so what's the point in using name?
URL Naming and Namespacing allow for 3 things:
A simple way to reverse URL match Class-Based Views. Though it is possible without it.
A way to distinguish URL patterns using the same view and parameters.
A way to differentiate URL names between apps.
(Click the links for an example of the issue and how naming/namespacing solves it)

The reason they probably added a namespace for the URL is so that they can do reverse namespaced URL.
For example in a template somewhere, you will probably see something like:
Click me!

Related

I get this error when I try to render some html files in django: NoReverseMatch at / Reverse for 'it_languages' not found

When I try to render a html file in django project, I get this error, and I can't see the localhost page 'cause of this.
The error is:
NoReverseMatch at / Reverse for 'it_languages' not found. 'it_languages' is not a valid view function or pattern name.
and it languages is url for in html
Then it bolds me with yellow this:
Home
About Me
**IT-languages**
Projects
Contact
I expect to see my offline page rendered by django project
Should I keep it like the original html version:
Home
About Me
IT-languages
Projects
Contact
Please start by providing your urls.py, views.py, and the it_languages template.
As #cbirch said, it's impossible to exactly provide an answer without more information (preferably the code they listed).
In general, the error 'NoReverseMatch' happens when you are trying to refer to an endpoint by the name, but the name doesn't map to a provided endpoint.
When you create a route you add an entry to the urlpatterns list in urls.py (typically) - if you don't give them a specific name, they will be given an automatically generated name. Then in your template file, if you refer to one of these names, they have to match!
Probably you use { url it_languages } or similar in one of your templates, but you haven't set that as a name for a url.
If you install django-extensions, there's a tool (show_urls) that will allow you to list your endpoints and their names (I believe) - that may help you trace the issue down. Good luck!

How to request URL of previous page visited and store parts of it as a ForeignKey?

I have a django application that has an architecture:
Myapp.com/< uniquepageURL>
For posting new things to the page:
Myapp.com/< uniquepageURL>/post
For commenting on a specific post on a page
Myapp.com/< uniquepageURL>/comment< ID# of the post>
For example, if you are commenting on the post that is stored in the database with an ID of 22 then the URL should look like:
Myapp.com/< uniquepageURL>/comment22
This is how I’ve decided to map my urls. Is there a better/simpler way to do it? The < uniquepageURL> is also the ForeignKey of the post object in my models. What I am having trouble with is figuring out how to use the request function in django to look at what the url was so as to gain information from it, namely for posts which uniquepage it is from so I can save the value into the foreignkey field and for comments which post ID it is a comment of. What would the views for each look like?
Here is my urls.py.
For posts:
url(r'^(?P<uniquepageURL>[a-zA-Z0-9_.-]*)/post/$', views.post, name='post')
for comments:
url(r'^(?P<uniquepageURL>[a-zA-Z0-9_./-]*)/comment(?P<post.pk>[0-9]*)/$', views.comment, name='comment')name='comment')ts:
I think the post.pk part is wrong since it returns an error. But I can fix that myself hopefully if I can figure out how to get the post section working at least.
Be aware that the ?P<uniquepageURL> syntax indicates a named group; Django will attempt to match that name to arguments in the view function (see https://docs.djangoproject.com/en/1.7/topics/http/urls/#named-groups).
So, to get that value passed to your view function, simply include a parameter uniquepageURL. Note that means post.pk won't work as a name; consider post_id as an alternative. (Though I supposed you could use a **kwargs construct and get at the value with kwargs['post.pk']).
That said, if you do need other information from the request URL, I think the value you are looking for is request.path (which presumes your signature is def comment(request, uniquepageURL, post_id) or similar.

How do I find where a django template variable comes from in the python

Is there a good general way of finding the line of python code responsible for passing in variables to django templates? When newly picking up a large code base, and I see {{ x.y }} in the template, and nothing obviously related (by how things are named) to x in the {% load ... %}, what do I do? Where can I find this variable in the python so that I can change it or related code?
My current solutions tend to be tedious and overwhelming. It's a lot of searching, but I would like to be able to just know where to look.
Look at the URL of the page. Then go to urls.py and look at which view is linked to the URL. Then open views.py and search for the view which the URL linked to.
In that view, the variable 'x' should be there. If it's not, then check the template context processors and middlewares as karthikr suggested.

Link to get http response works just once in django

I am having problem to get graphical result for second time either it be for a database query or two or more queries. For first time result is given as desired immediately but thereafter browser just says 'Connecting'. For example after http://localhost:8000/graph/ gives pie-chart for first time it does not give the pie-chart again when the same link is hit and also any other similar link http://localhost:8000/graph2/ doesnot work. The latter link would have worked if http://localhost:8000/graph2/ was hit first after execution of program.
In urls.py links are given as:
url(r'^graph/', graph, name = 'ngraph'),
url(r'^graph2/', graph2, name = 'ngraph2'),
Directory structure looks:
Detail code is given HERE.
Two options:
In your urls.py, add a separate pattern object with the prefix set as the views of your app. That would be like urlpatterns += patterns('welcome.views', url(r'^graph/', ...)). Rest should be as it is.
Dont change urls.py. Instead refer to the complete path in the template starting from your app. In your case that might be {% url welcome.views.ngraph %}.
Since you mentioned that GET is not being served at all, it is quite possible that the server cant locate (map) the url to the function.
In an ideal situation, you should import welcome.views instead of using from .. import * and polluting the urls.py globals. Use the complete path in the patterns object. This way you wont need separate patterns objects for different apps. This would make a lot of sense in a bigger project with more applications. But in any case, this is the standard practice and is encouraged.
Do post your result.

How do you add a new entry into the django admin index?

I'm working on a Django project, and I've created some custom admin views using the get_urls override method described in the documentation. It works perfectly. There is just one problem. There is no way to get to this custom admin view unless you already know the URL.
There are some ways I already know of to add a link to this view somewhere in the admin, but none of them are satisfactory. I want a link to the custom view to appear in the model listings right with all the model admins. I just don't want it to have +add or +change links next to it because it isn't a model.
I could just override the admin_site or the template, but this is no good. It puts the customization on the project level instead of the app level. It also will only put the link on the /admin/ page and not the /admin/myapp/ page.
I could also just easily add the link in a different location by overriding the app_index.html template, but that is not exactly a convenient or intuitive place to look for it.
Another solution I came up with is to create a blank model and register a blank admin for it. Then steal the url patterns for that model so clicking on its entry goes to my custom view instead of to a blank add/change view. That works, but it's an incredibly ugly hack.
Here is a picture of what I'm trying to achieve.
I still think the correct way of doing this is overwriting some parts of django admin templates. There is no easy way of adding these links.
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template
I also found this article http://coffeeonthekeyboard.com/o-hai-django-adminplus-568/ which also suggests that django-adminplus is a good tool for doing this. Personally I prefer to keep clear of any extra dependancies and would still use templates - but thats up to you.
Have you tried this app: https://github.com/jsocol/django-adminplus? Even if it does not work for the exact purpose you are trying to achieve, at least it can give you some enlightement by checking out the code
You need to override the template admin/index.html. Thenput a new pair of tags after the {% endfor %} on line 40.
You might also be able to solve it using jQuery.

Categories