Tuesday, 22 November 2011

Filter Records from Multiple Fields

this could be bit confusing that how to filter search records from multiple field from Model in django.

To filter records that contain "HJ" in Vendor field and their Rate are 0.14 then Query will be:
obj = TBR.objects.filter(Vendor__contains = "HJ", Rate = 0.14) OR
obj = TBR.objects.filter(Vendor__contains = "HJ").filter(Rate = 0.14)

To filter records that contains "HJ" in vendor field or their Rate are 0.14 then Query will be like this:
obj = TBR.objects.filter(Vendor__contains = "HJ") | TBR.objects.filter(Rate = 0.14)

Best of Luck

Sunday, 20 November 2011

How to Save and Update using Form using django

if you have used django forms and have inherited them using any Model which actually refer to table in database. on posting you could easly parse form like:

frm = CharacterForm(request.POST)

where CharacterForm is your Form which might inherit fields from Character Model. and Now you could Save this new Record using simple frm.save()

How about Update:

Some time you need to update record. to do this you will be required to bound that record to Model instance to do this update above form parsing line to:
frm = CharacterForm(request.POST, instance = Character.objects.get(pk = idofrecordtoupdate))

then simple use

frm.save()

this will update existing record instead of inserting new record.

Best of luck.

CSRF token missing or incorrect

if you are new to django then this problem occure often in forms and you messed up that problem didn't get resolved even if you use this Tag in form and use RequestContext instead of Context. So here is a simple soultion to overcome such issue:

Place tag {% csrf_token %} in form and go to views.py and import csrf using

from django.core.context_processors import csrf

Now when creating normal context like
c = Context({"frm":frm})
after this update Context using csrf
c.update(csrf(request))

Now this issue is resolved.

best of luck

Saturday, 12 November 2011

CSV Parser and Database

Here is how we can parse values from csv file and save records to database. inorder to do this first you need to define table structure in models.py.

Here is a sample Model:

from django.db import models
   
class Code(models.Model):
    code = models.CharField(max_length = 20)
    description = models.CharField(max_length = 40)

from django.http import HttpResponse
from django.template import Context,loader
from Code.models import Code
from django.shortcuts import render_to_response
import csv
import os

def readfile(request):
    func()
    t = loader.get_template('readfile.html')
    c = Context({"user":request.user,"entries":Code.objects.all()})
    return HttpResponse(t.render(c))


# reads-in the data from file
# looks for file in the given directory
# identifies file as having .csv extensions
# opening the file using CSV library
# reads the records line-by-line and save into database
def func():
    files = os.path.join('.','Media/Uploads')
    for f in os.listdir(files):
        fname = f.split('.')
        name , extantion = fname[0], fname[-1]
        if extantion == 'csv':
            csv_filepathname = os.path.join(files,f)
            dataReader = csv.reader(open(csv_filepathname), delimiter=',',quotechar='|')
            for line in dataReader:
                cc = Code()
                cc.description = line[0]
                cc.code = line[1]
                cc.save()
Best of Luck.

How to Display Comma Seperated File in Table using django Python

Common task for showing data could be to load a comma/Tab or any other character seperated file and display in table on webpage. this Could be achieved by simple Process. First Step is to design Template.
Here is html code with django template tags to be used as template. Remember here I have used Simple html and django template tags which will be rendered at the time of execution. if you need any information on how these tags works let you ask them in comments.

{tbr.html}

<html>
<head>
<title>
My Test Django App
</title>
</head>
<body>
<table style = "width:600px;background-color:#888888;" border = "2">
        <tr>
         <td>Header1</td>
         <td>Code</td>
         <td>Vendor</td>
         <td>Destination</td>
         <td>Rate</td>
         <td>Effective Date</td>
        </tr>
        {% for line in lines %}
        <tr>
         {% for rec in line %}
         <td>{{rec}}</td>
         {% endfor %}
        </tr>
        {% endfor %}
       </table>
</body>
</html>

Then in View.py Render From function called by URL and Define another function to read file.

from django.core.context_processors import csrf
from django.http import HttpResponse
from django.template import Template, loader, Context
import os;

def index(request):
   lines = ReadTBR()
   t = loader.get_template('Templates\\tbr.html')
   c = Context({"user":request.user, "lines":lines})
   c.update(csrf(request))
   return HttpResponse(t.render(c))
def ReadTBR():
  path = os.path.join('.','../tbr.out')
  tbr = open(path,"r")
  res = []
  for line in tbr.readlines():
    l = line.split('\t')
    rec = [l[0],l[1],l[2],l[3],l[4],l[5]]
    res.append(rec)
  return res

Saturday, 5 November 2011

Portable Apps in django - Share Apps

How to Share Applications in django to be shared among multiple projects?

This Questions comes into mind because one Projects consist one or many Applications and any application can be used in multiple projects as well. like blog app can be shared among multiple projects. to do this you need to copy app to Python Site-packages So you could simple add in Settings/Installed App by using there Name or Make another Folder of Apps and add that Folder to Python Path. To Add Apps Folder to Python Path. Edit Settings.py and Add Following Lines on to of it

DEVELOPMENT = True
if DEVELOPMENT:
    import sys
    sys.path.append('Path to Apps/Apps')

and if your Apps Folder Reside where your Projects are then you can edit above code as

DEVELOPMENT = True
if DEVELOPMENT:
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), "../Apps"))

* Remember do not forget to Remove DEVELOPMENT = False or Remove above Code When Deploying Project of Server

Please share your comments below.

Sunday, 30 October 2011

How to Use Css or Static Files in django Python

It is important to use static files in web application. one common item is Cascading style sheets (.css). Normarlly if you put css file even in where you placed template file but relative path to link css doesn't works. Because in django absolute path is required but its not a common practice. inorder to use static files you need to put them in folder. folder is better to be placed in root directory in your project. then make Modification to Settings.py & urls.py to Make that Folder accessable on domain to use them in your project.

e.g. if you have Named Static files folder myFiles then you can refer css file from your html Tag by /myFiles/style.css

you are required to make these changes:

  • In "settings.py", import "os.path"
import os.path
  • Change "MEDIA_ROOT", "MEDIA_URL" and "ADMIN_MEDIA_PREFIX" to
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "MyFiles")
MEDIA_URL = '/MyFiles/'
ADMIN_MEDIA_PREFIX = '/MyFiles/admin/' (anything other than media)
  • In "urls.py", include the following imports
from django.views.static import *
from django.conf import settings
  • And the following URL handler
# Required to make static serving work
(r'^MyFiles/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
Restart your server and it should be accessible from http://www.domain.com/MyFiles/style.css

Auto Settings Script

Here is Script copy and paste it to file and save file with static.py extention. Now copy that file in root of your django project where settings.py file is placed. Now run this Script

Script:
folder = raw_input("Enter Name for Folder in your Project Root! :> ")
contents = ""
for line in open("Settings.py", "r"):
    if(line.find("MEDIA_ROOT")>-1):
        contents = contents + "MEDIA_ROOT = os.path.join(os.path.dirname(__file__), \"" + folder + "\")\n"
    elif(line.find("MEDIA_URL")>-1):
        contents = contents + "MEDIA_URL = \'/" + folder + "/\'\n"
    elif(line.find("ADMIN_MEDIA_PREFIX")>-1):
        contents = contents + "ADMIN_MEDIA_PREFIX = \'/" + folder + "/admin/\'\n"
    else:
        contents = contents + line
if(contents.find("import os.path")==-1):
    contents = "import os.path\n" + contents
f=open("Settings.py","w")
f.write(contents)
#print contents
contents = ""
for line in open("urls.py", "r"):
    if(line.find("django.views.static.serve")>-1):
        continue
    contents = contents + line
    if(line.find("urlpatterns")>-1):
        contents = contents + "    (r'^" + folder + "/(?P<path>.*)$', 'django.views.static.serve', {\'document_root\': settings.MEDIA_ROOT}),\n"
   
#print contents
        if(contents.find("django.views.static import")==-1):
            contents = "from django.views.static import *\n" + contents
        if(contents.find("from django.conf import settings")==-1):
            contents = "from django.conf import settings\n" + contents
           
f=open("urls.py","w")
f.write(contents)
print "Now Create Folder Named " + folder + " on Root Dir and keep files you want there.\ne.g. if you have placed file t.css in sub Dir css\nThen you could find it at http:\\yourdomain.com\\"+folder+"\css\\t.css"
raw_input()