URLs stored in database for Django site - python

I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.
Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in the database table from the URL stored in the column rather than having to code a view and the URL for every page (which obviously defeats the purpose of a CMS)?
If someone can just point me at the right part of the docs or a site which explains this it would help a lot.
Thanks all.

You dont have to to it in the flatpage-way
For models, that should be addressable, I do this:
In urls.py I have a url-mapping like
url(r'(?P<slug>[a-z1-3_]{1,})/$','cms.views.category_view', name="category-view")
in this case the regular expression (?P<slug>[a-z1-3_]{1,}) will return a variable called slug and send it to my view cms.views.category_view. In that view I query like this:
#render_to('category.html')
def category_view(request, slug):
return {'cat':Category.objects.get(slug=slug)}
(Note: I am using the annoying-decorator render_to – it is the same as render_to_response, just shorter)
Edit This should be covered by the tutorial. Here you find the url-configuration and dispatching in every detail. The djangobook also covers it. And check pythons regex module.
Of course you can use this code.

Your question is a little bit twisted, but I think what you're asking for is something similar to how django.contrib.flatpages handles this. Basically it uses middleware to catch the 404 error and then looks to see if any of the flatpages have a URL field that matches.
We did this on one site where all of the URLs were made "search engine friendly". We overrode the save() method, munged the title into this_is_the_title.html (or whatever) and then stored that in a separate table that had a URL => object class/id mapping.ng (this means it is listed before flatpages in the middleware list).

Related

Django - beginner- what is the process for passing information to a view via a url?

I am working on my first django project which is also my first backend project. In the tutorials/reading I have completed, I haven't come across passing information back to django without a modelform.
My intention is to calculate a value on a page using javascript and pass it to django when a user hits a submit button on that page. The submit button will also be a link to another page. I know I could process the information in a view via the url if I knew how to pass the information back to django.
I'm aware that django uses MVC and as I have my models and views in place, I am lead to believe that this has something to do with controllers.
Basically, I would like to know how to pass information from a page to django as a user follows a link to another page. I understand that this isn't the place for long step by step tutorials on specific topics but I would appreciate any links to resources on this subject. I don't know what this process is even called so I can't search documentation for it.
EDIT:
From further reading, I think that I want to be using the submit button to GET or POST the value. In this particular case, POST is probably better. Could someone confirm that this is true?
Yes, generally POST is a better way of submitting data than GET. There is a bit of a confusion about terminology in Django. While Django is, indeed MVC, models are models, but views are in fact controllers and views are templates. Since you are going to use AJAX to submit and retrieve the data, you don't care about templates. So what you most likely want is something like this
in your urls.py as part of your urlpatterns variable
url(r'mything/$', MyView.as_view())
in your views.py
from django.views import View
from django.http import HttpResponse
class MyView(View):
def post(self, request):
data = request.POST
... do your thing ...
return HttpResponse(results)
and in your javascript
jQuery.post('/mything/', data, function() { whatever you do here })
There're many ways, you can achieve this in django. Following are the two ways, that I generally prefer :-
1) As a query string parameter in the URL
eg. http://localhost/getPatientInfo?patientId=23&name=Sachin
2) Making URL dynamic, to include the information in the view itself.
eg. http://localhost/patientInfo/23/Sachin
In case 1:-
You will have to do,
patientId = request.GET["patientId"]
name = request.GET["patientName"]
In case 2:
Your URL conf will be something like :
urls = [
url("^patientInfo/(\d+)/([^/]+)$", yourViewFunc)
]
And in your view func :-
def yourViewFunc(request, patientId, patientName):
# your logic goes here
pass
For info. related to URLConf, refer to https://docs.djangoproject.com/en/1.10/topics/http/urls/#example

Implementing Universal Search in a Django Application

We have a large Django application made up of a large number of different views (some of which contain forms). As with most large applications, we use a base layout template that contains the common layout elements across the applications (mainly a header and a footer), which the templates for all of our views extend.
What we are looking to do is create a universal search box in our application, accessible on every page, which allows users to perform searches across the entire application, and want to place the search box inside the header, which involves placing a form inside our base layout template. This means that every view in our application will need to be able to handle the submission of this search form. Once this search form is submitted, we will need to redirect the user to another view containing the search results.
However, we are struggling to come up with a pattern to handle this. Does anyone know of functionality built into Django that will help us to build this? Failing that, can anyone suggest a good strategy for modifying our application so that we can handle this use-case without having to modify a large number of existing views (which we don't have the resources to do at the moment)?
Please note that the focus of this question is intended to be the best way to handle the submission of a form which appears in every view, and not strategies for implementing a universal search algorithm (which we have already figured out).
Ideas Explored So Far
Our first idea was to create a base View class that implements handling the universal search form submission, and have each of our views extend this. However, this is not possible because we already have views that inherit from a number of different Django view classes (TemplateView, ListView, FormView and DeleteView being some examples), and to be able to build our own common view class would mean either writing our own version of these Django view classes to inherit from our own view base class, or re-writing a large number of our views so they don't use the Django view classes.
Our next idea was to implement a mixin that would handle the universal search form submission, in an attempt to add this functionality to all our views in a way that allows us to continue using the different Django view classes. However, this brought to light two new problems: (a) how could we do this without modifying each of our views to become a form view, and (b) how can we do this in a way that allows the form handling logic to play nicely when mixed in to existing FormViews?
This seems like such an obvious question that maybe I'm overlooking something. But as others have said your universal search form should not make a POST request to the view that rendered the current page.
Each html form has an action attribute. The attribute of your search form should point towards an URL. Probably something like /search. That url would have a view behind it that handled the POST request from the form and returned the search results. Django has URL template tags to make this easy. {% url 'myapp.views.search' %} will give you the correct url for the search view function if it lived inside the views module in myapp. So the relevant bit of html in your base template would be something like:
<form action="{% url 'myapp.views.search' %}">
<input type="text" name="qs" placeholder="Search">
</form>
If you are planning on displaying the search results on a new page there is absolutely no need to return JSON or anything like that. Just have a search view that looks like this
def search(request):
query = request.POST.get('qs', '')
results = SomeModel.objects.filter(name=query) # Your search algo goes here
return render(request, 'search_results.html', dict(results=results))
Instead of handling the form submission on every view of the application, you can implement a separate view (endpoint), which handles all the search queries. (an endpoint which returns JSON result) since you dont want to add overhead of rendering the whole page with that view. So the search query (which client side AJAX performs to the webserver) will return JSON response, and the Javascript can render that response. This way you can keep the search view isolated from the rest of the views. (Django REST will be helpful in this case)
And this search form will be included in your base template, so your search box is accessible from the entire application, and it submits to the same view. And the AJAX function will handle the server response for rendering it.
It seems like you just need to create another SearchView which takes the query and displays the results. I am not sure if the results have to be displayed differently depending on which page the search has been performed from but it does not seem like.
The form would not have anything to do with the other views. You could just hard code it in the base template.

url design: ways to hide pk/id from url

To access the details page of an Item on my site, one would use the following url
<mydomain>/item/1
where 1 is the primary key of the Item
I am looking for a solution that allows me to redesign the url with the following requirements:
exclude pk or any sequential ids from the url
be able to uniquely access the Item details page
I intended to ask this as a general web design question, but just thought I should mention that I am working with Python/Django.
You need to have some kind of identifier in the URL, and this identifier:
must be unique (no two objects can have the same id)
must be permanent (the id for an object can never change)
so there aren't all that many options, and the object's primary key is the best choice. If for some reason you can't use that (why not?) you can encode or obfuscate it: see this question and its answers for some ideas about how to do that.
Stack Overflow's own URL design is worth a look. You can reach this question via any URL of the form
https://stackoverflow.com/questions/9897050/any-text-you-like-here!
This allows the URL to contain keywords from the question's title (for search engines) while also being able to change when the title changes without breaking old links.
I don't like the slugfield option because it adds an additional query to the database.
I did the following in a project:
My URL looks like this:
<domain>/item/5927/728e26e9464a171b228bc9884ba3e4f76e2f8866/
This is:
<domain>/item/<id>/<hash>/
If you don't know the hash you can't get to the item:
urls.py:
url(r'^item/(?P<id>\d+)/(?P<hash>\w+)/$', 'rwapp.views.item', name='item')
views.py:
from hashlib import sha1
def item(request,id=None,hash=None):
if not id:
return HttpResponseRedirect("/home")
if hash:
chash = sha1("secret_word%s"%id).hexdigest()
if not chash==hash:
return HttpResponseRedirect("/home")
else:
return HttpResponseRedirect("/home")
Of course, every time you render the URL you have to add the // part.
For Django, you can give your models a SlugField, then have the view look up the model using that.
MyModel.objects.filter(slug_field_name='some-slug-value')
Make sure some form of uniqueness constraint is on it.
Well there are a lot ways to do this. Since you are using django, take a look at SlugField. Or you generate UUID and store it on each item for access.
One dirty way of doing this would be to use a cookie to hold the id of the object being requested. I don't particularly like the idea and it might be very difficult to get a framework to support unless you have experience writing/extending frameworks.
Some frameworks support using an id= attribute instead of your URL path. If this is included as a POST parameter it will not be visible, but linking pages together with POST would be challenging as it is intended for the submission of form data.
The method I would suggest, is to use something besides ids to uniquely identify your objects if this is a real requirement. Then include that in your URL. While this is not an ideal design from the database perspective it does have benefits. First you must consider why you want to hide this information. If it is for SEO purposes, using a name of the item rather than its id is what you want in the URL. The real problem is that if you just hide this information in some other data channel you then have the same URL for different resources. This is sub-par for many reason not the least of which is SEO and user bookmarks. Using a human readable key resolves both situations and others, while infuriating your DBA. Using this method should also work easily into a framework either directly or by using additional code in the controller to make the translation, which might set you right with the DBA.

Is there a way to have something execute for every view in django?

I'm new to Django and coming from Rails, so that may explain my odd questions below:
I have a main layout that has a sidebar that lists the latest updates to the site. That main layout is used for every page in my webapp so every template that is created extends main.html.
For the latest updates section, I just want to get the last 5 updates from posts to the web app every time a page is rendered. I thought about making the sidebar do this through an ajax call once the page is loaded, but I thought this may not be my best option.
I also considered creating a tag to do this for me and then just calling the tag inside of main.html. This is simple enough, but I'd have to write a lot of HTML inside of the tag code, which seems to be a little annoying (a lot of string appending and such, unless I'm wrong and there is a better way?)
I have read about Context Processors. This seemed to be exactly what I wanted, but it appears this may cause another issue where I have to pass a context_instance to every single render_to_response? This appears to be a lot of code repeat and I'm trying to avoid that if possible. Is there a way to just make render_to_response always take the RequestContext object without always having to specify it?
Are there any other ways to achieve having some code run for every view and eliminate the need to always pass data to a view?
Django 1.3 added the render shortcut which is the same as render_to_response but with RequestContext automatically used.
Templates is a appropriate place for this: the variant with custom tag and template inheritance is simple and convenient. To avoid string appending use mini-template just for your tag: it is called inclusion tags.
I would definitely go for the Ajax call, it is as simple as to create an small view which queries the model for the 5 latest posts, serializes them into json or xml data, and returns them in your HttpRequest object.
You can use direct_to_template instead of render_to_response.

How do I form a URL in Django for what I'm doing

Desperate, please help. Will work for food :)
I want to be able to have pages at the following URLs, and I want to be able to look them up by their URL (ie, If somebody goes to a certain URL, I want to be able to check for a page there).
mysite.com/somepage/somesubpage/somesubsubpage/
mysite.com/somepage/somesubpage/anothersubpage/
mysite.com/somepage/somesubpage/somesubpage/
mysite.com/somepage/somepage/
Notice I want to be able to reuse each page's slug (ie, somepage/somepage). Of course each slug will be unique for it's level (ie, cannot have two pages with mysite.com/somepage/other/ and mysite.com/somepage/other/ because they would in essence be the same page). What is a good way to do this. I've tried to store the slug for a page ('somesubpage') in a field called 'slug', and make each slug unique for it's parent page so that the above circumstance can't happen. The problem with this is that if I try to look up a page by it's slug (ie, 'somepage'), and there happens to be a page at mysite.com/other/somepage/ and mysite.com/page/somepage/, how would my application know which one to get (they both have the same slug 'somepage').
You need to also store level and parent attributes, so that you can always get the right object.
The requirement to store hierarchical data comes up very frequently, and I always recommend django-mptt. It's the Django implementation of an efficient algorithm for storing hierarchical data in a database. I've used it on several projects. Basically, as well as storing level and parent, it also stores a left and right for each object, so that it can describe the tree and all its sub-elements uniquely. There are some explanatory links on the project's home page.
It sounds like you're looking for a CMS app. There's a comparison of several Django-based CMS. If you want a full-featured CMS at the center of your project, DjangoCMS 2 or django-page-cms might be the right fit. If you prefer a CMS that supports the basic CMS use cases but goes out of your way most of the time feincms could be something to look at.
edit: incidentally, most of the CMS on the comparision page use django-mptt that Daniel mentions.

Categories

Resources