Monday, August 25, 2014

Django Templating Language - Part I

Hey guys! I know I haven't posted anything in a very long time. Exigent circumstances. Anyway, now I'm back with what may well be the most important skill in your entire Django toolkit. The templating language that Django ships makes writing pages that display multiple results mundanely easy.
In this part I'll only introduce you to templates. We'll see how to render them in the next one.

Variables:
We all know what variables are and how important they are for programming. This is how variables are represented in Django:
{{ variable_name }}

It can also be written as {{variable_name}} but the former is more readable. Let's see how to 'declare' a variable in an HTML script:

<h1>{{ heading }}</h1>
<form action = "/foo/" method = "post">
    <input type = "text" name = "bar" placeholder = "{{ placeholder }}">
</form>

Notice the difference? {{ heading }} is without quotes and {{ placeholder }} is with. The basic concept is you write the name of the variable exactly as you would write normal text. While writing normal text, you would not put quotes between the <h1>...</h1> tags but would in the <input> tag.

Right now if you just write this much code it'll print all raw data. There is no use of this code yet. However, we'll see how to render context to these templates soon enough.


Tuesday, June 17, 2014

Enforcing case sensitivity in databases

Hey guys! When I was developing today I realized that the username primary keys were not case sensitive. This is a big drawback. It reduces the number of unique and viable usernames. Even though this number is still gargantuan, case sensitive usernames are a must everywhere.
The demonstrate my problem, here's what was happening:
nitin was a username registered on my site. It was allowing entry and showing the same account when logged in with Nitin, nItin, and so on. There are 32 possibilities (2^5) of nitin being spelled with either upper or lower case characters.
Thus, 32 possible user accounts were being mapped on to only one. To do this, the username has to be checked in the query itself.

Now, select something from some_table where username = "nitin" would give you the same result for all 32 possibilities of nitin.

To avoid this, the query has to be altered:
select something from some_table where binary username = "nitin"

The binary checks for case also.
Cheers!

Thursday, June 12, 2014

File download script

Greetings! If you recall, a while ago we saw how to write a file upload script. File download is also equally important. Let's see how to write a download script now.

def download (request):
    filename = "/foo/bar/%s.%s" % (name, extension)
    f1 = open (filename, "r")
    response = HttpResponse (f1, mimetype = "type/extension")
    response['Content-Disposition'] = "attachment; filename = foo_bar.extension"
    return response


Ok, now let's examine this code:
  • Specify the file name
  • Open this file in read mode
  • Create HttpResponse object with the following parameters: filename, and mimetype.
  • MIME stands for Multipurpose Internet Mail Extension.
  • Here's a list of all MIME types. Find the appropriate one for the extension you want: http://www.sitepoint.com/web-foundations/mime-types-complete-list/
  • The second filename in the last but one line is the name and extension which the downloaded file should have. For example, your file may be .py, but you might want to make it download as .txt
  • Finally, return the HttpResponse object, and et voila! You have your file ready for download.
Note: As usual, this download will be triggered when the URL that points to the function download in the particular view is accessed.
Cheers!

Monday, June 9, 2014

The SaaS methodology

Hey guys! This one's not a tutorial. So just sit back with a cup of coffee and relax. I assure you this is going to be fun.
Up until now we've seen two names associated with programming in Django. The first one is Web Design, which is very mundane. Any Tom, Dick and Harry can visit a CMS like Wordpress nowadays and make a website for themselves.
Then we saw the slightly more colorful and yet highly misunderstood name Web Application Design, or simply Web App Design.
I'm finally going to tell you a name that is not only prestigious, but one that will blow your mind whole. It's SaaS, or Software as a Service.
I'll give you a minute to let the awesomeness sink in.
Done?
Good.
Yes, Django programming falls under software. People think that software only means the ones we open on our computers.
The Service in SaaS is not service as in social service. It means the service you provide to computers.
SaaS pieces are hosted on servers and can be accessed from anywhere with an Internet connection. They may be free or charged. The charged ones are called Proprietary Software. Also note that the free ones are not called Open Source. That's completely different. Open Source is when the underlying code is visible to the general public. Proprietary software may also be Open Source.
Furthermore, SaaS may be for only a company or organization in general or may be publicly usable. In the first case, it is hosted on indigenous servers, whose access is restricted to only within that organization. In the second, they would normally be hosted on a global server.
So how does SaaS make money? There are many models currently employed:
  • Developers can charge on a time basis (i.e. weekly, monthly, fortnightly etc) that will enable the users unlimited utility out of the software.
  • They may charge a small amount every time the software is used, which then limits the usage. This one sometimes is a bigger money maker.
  • They may also charge a very high one time price, which would transfer the ownership of the software to the buyer. The developers may further charge on maintenance and repairs.
So why did I write this article? When I first found this out several months ago while talking to my Dad (very wise man), it made me develop in Django in more earnest, all the while thinking, "Hey! I'm developing software!"
SaaS is also used while talking about RoR (Ruby on Rails). Currently the number of Rails developers greatly outnumber that of Django.
So I guess I'm hoping that by reading this article more people will be encouraged to become Django coders. Forget Sparta, we'll stand in front of Rails developers and say "THIS IS DJANGO!!".
(I have absolutely nothing against Rails or its developers by the way)
Cheers!

Sunday, June 8, 2014

An important thing

Hey guys! This is an important one. This had me stymied for a day and a half. Do not forget to commit the changes before closing the connection in the particular view if that view contains any of insert, update or delete queries. It doesn't matter with select queries, but for the aforementioned it is a must.

Friday, June 6, 2014

Displaying images

As I mentioned in a previous post, <img src = ""> does not work in Django. I mean, it does work, and that's how we are going to display images, but it doesn't work if you give local machine addresses like /home/foo/bar or C:/images/foo/bar. This is actually a good thing. Django has a very sophisticated method of handling images and other files, often called as static files.
If you open your settings.py file, you'll see two URLs: STATIC_URL and MEDIA_URL. These can be used to render static files and media in general.
Now there are two ways of doing this:
  • Using the in-built {{ STATIC_URL }} or {{ MEDIA_URL }} variables. But as I have not posted about Django's templating language, we'll put this one on the back burner. But rest assured, once you understand the templating language, how to use these will be self-evident.
  • Using full URLs, including the values specified in {{ STATIC_URL }} and {{ MEDIA_URL }}
We'll be using the second method. The only disadvantage of this method is that if the directory containing static files changes then you have to make sure that change reflects in all templates. In the first case, this would happen automatically.

Let's assume you're running your website on localhost, i.e. http://127.0.0.1/ and you want to render an image on the URL http://127.0.0.1/home. Let's also assume that the .html file behind this webpage is called home.html (wow, that's a lot of assuming).

Anyway, change into your project directory, and create a folder called static. Store all your images here. Let's assume (not again!) that you have an image called garden.jpg in the static folder, which you want to display on the homepage.

So instead of giving local machine paths, you give the path in the form of a URL.

<img src  = "http://127.0.0.1/static/garden.jpg">

Now, to validate this, open your settings.py file, and make the following changes.

STATIC_ROOT = "/foo/bar/mysite/static"
STATIC_URL = "/static/"

This will tell Django that when http://127.0.0.1/static/ (or STATIC_URL) is accessed, the path in STATIC_ROOT is to be checked.

That's all for now! Two things before we part:
  • I'm still working on the templating tutorial, to make it concise as it is a very vast topic. Once I come up with it, we'll investigate the {{ STATIC_URL }} and {{ MEDIA_URL }} business.
  • What we did here with static can also be done with media. They are two objects of the same file displaying facility, giving us more customizability. To use media, just replace static with media in all of the code above.
Cheers!

Tuesday, June 3, 2014

Backing up

Backing up your files is extremely important. If the server you've hosted your site on crashes and you don't have a copy of the files then your goose is cooked. You'll have to start from scratch.
I've written the code for backing up files and your MySQL database. Here's the link:

https://github.com/AgentK1729/File-Backup

In case you have an SQLite database, there's no need to back up the database as shown in the code, there'll be a readymade .db file. Just copy it somewhere reliable.