31 Jul 2013

Code that i love and that i hate

A programming language is a  set of specification and rules. It is better to stick to those while you are coding.
Anyone having basic arithmetic ability and knowledge of for loop can code a Fibonacci series.  Since one can understand the problem and apply his/her logic to solve. But writing a good code and writing a code is two different things.
Writing a code is just like typing the problem logic and make it work. Whereas the writing a good code is to present it beautifully so it looks like a piece of art.
A "good code" has to be well structured, clean and understandable.


Good code

Using appropriate names for variables , functions, classes etc.
Comment as much as you can , for which is not obvious .
Divide whole problem into modules.
Proper indentation.
Logical organization of statements.
Appropriate error handling mechanism.
Prefer clarity to "efficiency" read as premature efficiency.
Declare where you use or declare all data at same place.
Choosing appropriate data structure for the problem.
Code as per the the programming language's style conventions or standards.


Code that i hate to work with.

Basically it will be a right opposite of "good code". To name a few
naming variables to anything rather than some meaningful name.
Consistently bad indentation.
No comments to important parts of code.
Code striving for premature efficiency.
Repeating same code which is better to be modularized.
Doing more that one thing in a module.




But in real work environment one has to work with other fellows who habitually wrote opposite of "good code". They tends to follow writing style rather than coding style.
And when you are sharing your code to such a guy and he is making changes to it .. which will diminish the beauty of your code, then you have to write this post and ask them to go through it.




30 Jul 2013

Serving uploaded images in Django

I ran into trouble while serving the uploaded images from database in template. In this post i'll  share what mistakes i made and how i rectified those mistakes.

Problem was :
In template the uploaded image was not showing like
{% for movi in all_movies %}
<div class="movie_frame">
<img src="{{MEDIA_URL}}{{ movi.poster}}" alt="xxx" height="140" width="110" />
</div>
{% endfor %}


For uploaded files one needs to set the MEDIA_ROOT and MEDIA_URL setting in settings.py.
setting.py
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'

Note:
MEDIA_ROOT is a absolute physical location where the images are to be stored. This will create a 'media' folder under SITE_ROOT.
MEDIA_URL  is url reference which is to be used inside template to get the image.


Mistake 1: The value of MEDIA_URL is same as the MEDIA_ROOT value i.e. "media".


Correction : changed the MEDIA_URL value from "media" to "/site_media/". you can give any valid string but make sure it should not be same as of MEDIA_ROOT value.


models.py
from django.db import models
from imdbclone.settings import MEDIA_ROOT
class Movies(models.Model):
    title = models.CharField(max_length=50, blank=False)
    plot =  models.CharField(max_length=500, blank=True)
    actors = models.CharField(max_length=200, blank=True)
    poster = models.ImageField(upload_to=MEDIA_ROOT, blank=True)

here poster will save the image to MEDIA_ROOT which is already been there, that initially i thought.

Mistake 2: upload_to attribute of ImageField is MEDIA_ROOT , is wrong.

Correction : poster filed in database will have the absolute path to the image like /home/navyad/workspace/imdb/imdbclone/imdbclone/media/media/image.jpg, which is wrong.
I changed the upload_to attribute value from MEDIA_ROOT to "poi" (any valid string will work).
Note :
      a)  Corresponding to upload_to value a folder will be created, in this case "poi". This folder will be             created under MEDIA_ROOT. And this is where the image actually stored.
      b)  poster filed in database it will contain image reference like poi/image.jpg,



movies/urls.py :
from imdbclone import settings
from django.views.static import serve
urlpatterns = patterns('',
                           url(r'^site_media/(.*)$', serve, {'document_root': settings.MEDIA_ROOT}),  
)
In template when image is to be displayed using <img src ..> tag , it will make the request to get image. For that we have specified the url.

Mistake 3: placing url for image in wrong file.

Correction : I was using this for movies app and i placed the url for image in movies.urls , which supposed to be in the project main urls.py file alongside where setting.py live.

After correcting all the mistakes , and when image is loaded in template, i found this observation.
The <img src="" /> value  will be like
<img width="110" height="140" alt="xxx" src="/site_media/poi/image.jpg">
note 
src value : MEDIA_URL/upload_to/imagename


With these mistake i have learned how to serve the uploaded content using MEDIA_ROOT and MEDIA_URL.
At end i will share this quote :
If you're not making mistakes, then you're not doing anything. I'm positive that a doer makes mistakes.
John Wooden 

25 Jul 2013

Error: That port is already in use

I was having a trouble to restart a Django server. At first time , i started a server like
>>python manage.py runserver 192.168.1.5:8000
no problem it started running fine.

I had to change the models so i exit the server using ctrl-Z and issue command to create the tables
>>python manage.py syncdb

Now when i tries to again start the server by issuing
>>python manage.py runserver 192.168.1.5:8000 again ,
it returns error message Error: That port is already in use.

This error means that port is already in use and to use same port , first we needs to kill process running on that port. Which involves following two steps :

1. Finding process for port 8000
  >>sudo netstat -lpn |grep :8000
this will return something like:
tcp        0      0 192.168.1.5:8000    0.0.0.0:*        LISTEN      10797/python   

here 10797 is a process id running on port 8000.

2. Kill the process
   >>kill -9 10797

Now
>>python manage.py runserver 192.168.1.5:8000 
would start the server again successfully.



4 Jul 2013

Django path in your system

Django path in your system depends upon on how you have installed Django in your system.

If you have installed Django through pip installer then it should be like
'/usr/local/lib/python2.7/dist-packages/django/ 

If you have installed Django manually i.e. by downloading Django-X.Y.tar.gz file then
Django will be installed in you python installation directory under /site-packages/ directory


Finding Django path
There different ways you can find that out. 
the django path may vary depending upon the OS you are using,following examples are for ubuntu12.04.

>>> import django  
>>> print django.__file__  
'/usr/local/lib/python2.7/dist-packages/django/__init__.py'

or

>> import inspect  
>> import django  
>> print inspect.getabsfile(django)
'/usr/local/lib/python2.7/dist-packages/django/__init__.py'

or

>> import django
>>django

 or

>> import django
>>django.__path__