Tuesday, June 4, 2013

ASSIGNING VALUES TO DJANGO FORM BEFORE SAVING (Assigning default values to django form)


Sometime you need to exclude certain fields becuase they are not of much importance while taking input form the user. In that case If you have not included the fields in the form and wish to fill it with some data before saving then you are reading the appropriate post.

in the views file write a simple function as you could have written for the other forms. The difference is that instead of calling the form.save(commit = True) method you need to call form.save(commit = False), then do the processing on the posted data and then save it by calling the save() method. The sample code is given below to elaborate further.

The image given below contains only three fields out of six in the model. I will take input form the user in the three fields bit save data in all the six columns. Lets have a look how that is done.




Keep in mind that if you have made the forms from models then this will automatically be saved in the fields that you have made visible on the form. I have written this sample just to elaborate that different processing can be done when the data is posted. I have tried to explain by simply saving the posted data in excluded form fields. The fields description and type are not visible on the form, but when the form is submitted these fields will also be filled with the data.

def add_record(request,template):
    if request.method == "POST":
        # Its the name of the form in the forms.py file
        form = RecordForm(request.POST)
        if form.is_valid():
            # Instead we called this method to tell dont save data because we
# have to perform a job
            temp = form.save(commit=False)
            # the type is a column in model so i am saving "v" in that column
            temp.type = 'v'
            # description is another field in the model, so i am saving posted 
xml in that field as well for backup            
            temp.description = request.POST["xml_dump"]
            #Now saving the form          
            temp.save()
            response = {'status':True,}
        else:
         
            t = Template("<ul>{% for field in form %}\
                            <li>{{field.label_tag}} : {{ field.errors|striptags }}</li>\
                            {% endfor %}</ul>")
            c = Context({"form": form})
            response = {'status':False,'errors':t.render(c)}
     
        message = "Record added successfully"
        return render_to_response('done.html',{'message':message}, context_instance=RequestContext(request))
    else:
        form = RecordForm()
    return render_to_response(template,{'form':form}, context_instance=RequestContext(request))

Sunday, May 26, 2013

JAVASCRIPT REGEX FOR NUMERIC, NUMBER AND SPECIAL SYMBOL

People often ask for a javascript regex for validating input. normal regex are available but if anyone is interested in a regex expression for valiating input that should contain alpha-numerics and special character then below is the code for validating this type of input.

/^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z])(?=.*\W).*$/;

This regex can be divided into several parts
the first part (?=.{8,}) tells the minimum length should be 8. You can change it by replacing 8.
the second part (?=.*\d) tells that there must be a number 
the third part (?=.*[a-zA-Z]) tells that allowed alphabets are a-z and A-Z and it is a must
the fourth part (?=.*\W) tells that there should be at least a symbol

Now if you want to impose that password should contain alphabets, numeric  special character and at least one capital alphabet the it should be slightly changed to become
/^.*(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\W).*$/;



Below is illustrated code with HTML to show how the expression will work.

<script language="javascript">
function validate()
   {
    var pattern = /^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z])(?=.*\W).*$/;
    if (!pattern .test(document.getElementById("password").value))
    {
        alert("Password should be a cobination of alpha-numerics and a special          symbol with at least 8 characters")
    }
    else
     {
         alert("Validated");
     }
}
</script>
<input type="text" name="password" id="password" value="" />
<input type="button" value="Submit" onclick="validate()" />


Sunday, April 7, 2013

ADDING AUTOCOMPLETE, AUTOFOCUS, PLACEHOLDER AND OTHER ATTRIBUTES TO DJANGO FORMS

In HTML its easy to give just an attribute to a tag to set autofocus or autocomplete on/off. In Django forms the way around is a little different from the traditional way.
In HTML you can set a placeholder like
<input name = "name" placeholder = "Awais Ali" type = "text" />
So in Django you can do this by
self.fields['Name'].widget.attrs['autofocus']  = 'on'
You can also assign auto-complete in a similar fashion
self.fields['Name'].widget.attrs['autofocus']  = 'off'
Similarly place-holder can be set like this
self.fields['Name'].widget.attrs['placeholder']  = u'Your Name'
This can also be set using  dictionary by giving key, value like this
self.fields['Name'].widget.attrs({'placeholder':'Your Name'}) 

So over-all if you want every field to have some property or value then here is the code how to do it


 def __init__(self, *args, **kwargs):
        super(LoginForm,self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['autocomplete'] = 'off'
        self.fields['username'].widget.attrs['autofocus'] = 'on'
        self.fields['password'].widget.attrs['autocomplete'] = 'off'
 
    username = forms.CharField(label=_("Username"), max_length=30, widget=forms.TextInput())
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput(render_value=False))


So after putting this code in your forms.py you would achieve the required functionality. Similarly you can go on adding HTML attributes form here whatever you like to add for example:
read-only, disabled, multiple etc.

Feel free to ask if you have any queries in the comment below.


Wednesday, April 3, 2013

CONFIGURING DJANGO, APACHE AND MOD_WSGI ON CENTOS (Freshly Installed)

A lot of people have been asking me about the django configuration and its installation. I published a post regarding its installation. Its quite easy because you don't have to do anything you just need to run a script and its installed. The next thing is configuring django on Cent OS. So i thought of writing a post for newbie's to Linux and django environment to make them configure django on a freshly installed Cent OS

If the Cent OS is freshly installed then it would not have pip and easy_install. So first we need to install these tools. Its not mandatory but pip is used for installing and managing Python packages. Easy_install   is used for downloading, installing, uninstalling, upgrading and building python packages easily.



Easy_Install:wget http://peak.telecommunity.com/dist/ez_setup.pypython ez_setup.py
PIP
easy_install pip 


Now that you have installed the main python tools. Its time for some dependencies to be installed 

It will save a lot of time if they are installed on this stage and prevent errors that will pop in future during the process.
Dependencies:
  • yum install httpd-devel
  • yum install make
  • yum install gcc(compiler to make/complie C files)
  • or alternatively yum install python-devel
  • or alternatively yum install gcc-c++
  • yum install MySQL-python 

Now that dependencies are installed we are good to go.
INTALL DJANGO
pip install django
INSTALL MySQL
yum install mysql mysql-server 
INSTALL HTTPD   
yum install httpd. Type the command service httpd restart to check the status you can type service httpd status. 
INSTALL MOD_WSGI    yum install mod_wsgi 
If this command does not work properly then install manually through wget command



      tar xzf mod_wsgi-2.6.tar.gz
      cd mod_wsgi-2.6
      ./configure --with-python=/usr/bin/python2.5
      make
      sudo make install


Now change mode of wsgi file so that it can be called from httpd


chmod 755 /etc/httpd/modules/mod_wsgi.so

Now we have to edit httpd.conf
vi /etc/httpd/conf/httpd.conf 
Edit and add the given line in LoadModule section

LoadModule wsgi_module modules/mod_wsgi.so
Add WSGIScriptAlias
WSGIScriptAlias / /var/www/sitefolder/<project>/wsgi.py 

Paste these few lines that are necessary to show your required folders. I have to do this in my case beacause i have similar folders in my site
AliasMatch ^/([^/]*\.css) /var/www/sitefolder/<project>/static/css/$1AliasMatch ^/([^/]*\.[jpg|gif|png]) /var/www/<sitefolder/<project>/static/images/$1 Alias /media/   /var/www/wtoolgui/sitefolder/<project>/media/Alias /static/  /var/www/wtoolgui/sitefolder/<project>/static/  <Directory /var/www/<project>/static/ >    Order deny,allow    Allow from all</Directory>  <Directory /var/www/<project>/media/ >    Order deny,allow    Allow from all</Directory> WSGIRestrictStdout Off 

Now that you have done all the settings you need to make a wsgi file and place it into your project directory
vi /var/www/<project>/wsgi.py

Paste the given code into the file
import osimport sys path = '/var/www/<project>/'if path not in sys.path:    sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = '<project>.settings' import django.core.handlers.wsgiapplication = django.core.handlers.wsgi.WSGIHandler() 
Now you are all set up to make a django project. Make models after creating app and then run the command python manage.py syncdb to add those tables in the database.

Enjoy Python and Django and make applications.
Feel free to ask any queries in the comments below.





Thursday, March 21, 2013

ASSIGNING A QUERY RESULT TO DJANGO FORMS AND ASSIGNING A CLASS TO A DJANGO FORM FIELD

In Django if you chose to make forms from the models. Its really easier in a sense that you don't need to describe a separate HTML defining each and every field. By calling some Django forms functions things can be easily validated so you no longer need POST's to fetch data from html field. Just post the form and the Django will take care of all the other stuff.

In this post i am going to describe how to assign jquery classes and filtered queries to forms field in order to assign them some filtered data before they are shown on screen.
So you need to navigate into the forms.py file and write a little code


class FormName(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(FormName, self).__init__(*args, **kwargs)


Now Assign the queryset or the jquery classes in init function
If  you want to assign a query set then write django query like the one given
self.fields['author'].queryset = Author.objects.filter(Books__title__icontains = "Beautiful")
If you want to assign a JQuery class then follow the code written below
self.fields['author'].widget.attrs['class'] = 'required'
The "required" class is the class that is written to validate that the field on which it is applied must not remain empty.


        ajax = true
        data = {}
        $('.required').each(function(){
            $(this).css('border', '1px solid eee');
            data[$(this).attr('author')] = $(this).val()
            if ($.trim($(this).val()) == "") {
                $(this).css('border', '2px solid red');
                ajax = false
            }
            else
            {
                $(this).css('border', '1px solid #A9A9A9');
            }
        })

This is the required class that is placed in my .js file. So using this way you can asssign a dataset and jquery classes to django forms field.

Saturday, March 9, 2013

INSTALLING PIP ON WINDOWS

Sometimes you need to use utilities of Linux on windows as well. So if you want to execute commands in the command prompt just like linux shell follow this post.


1. Download and uncompress the latest pip version from here






2. Now you need to download the installer for Windows so you need to follow this link and downloa exe file and install it.




3. Now you need to copy the pip folder's content(not the folder) in the folder where your python is installed. A path like C:\Python2X(X means the version of your python) directory.


4. Add your python c:\Python2x\Scripts to the path. See my this post to get an idea how to add environment variables to path

You are good to go. Type pip install <package_name> and you are done.
Happy Linux life in Windows...:)








Sunday, March 3, 2013

INTALLING DJANGO FROM PYTHON (the smart way)

To Install Django you don't need to download it from somewhere else. If you have Python installed in your PC you can do this swiftly and easily by following this post.

First you need to move into directory where your Python is installed by typing the command in command prompt
cd C:/Python2.X 

Now you will see a Scripts directory in Python folder. You must have Scripts in your Python Path. You can do this by adding semicolon(;) and appending C:\PythonX\Scripts just like you did while installing Python. To see how to set environement varaibles check the first screen-shot of my THIS post. So going on type the command
cd Scripts
Now type the command to install Django
easy_install django

If you follow any issue while following this post then you must first install setuptools for windows. You can read more about it here

Wednesday, February 6, 2013

INSTALLING SCRAPY ON WINDOWS 8 (Web Crawling)

Scrapy is framework to crawl website and extract structured data from their web pages. To install scrapy on Win 8 their are some dependencies that needs to be installed first. This post will list them accordingly. Keep in mind that i have python 2.7 installed on my system and win 8. So if you have a different version of python select packages accordingly

After installing Python, follow these steps before installing Scrapy:
Add the C:\python27\Scripts and C:\python27 folders to the system path by adding those directories to the PATH environment variable. You can do this by control panel > system and security > system > advanced system settings and scroll down to PATH variable, click edit and add the path to the end after adding a semicolon ( ; )

  1. Install OpenSSL by following these steps:
  2. Go to Win32 OpenSSL page


  1. Download Visual C++ 2008 redistributables for your Windows and architecture
  2. Download OpenSSL for your Windows and architecture (the regular version, not the light one)
  3. Add the c:\openssl-win32\bin (or similar) directory to your PATH, the same way you added python27 in the first step`` in the first step
  4. easy install for python in windows. http://pypi.python.org/pypi/setuptools
Use setuptools for installing lxml and zope-interaface. Just got command line, go into directory where packages are placed and then type easy_install "package_name.egg". This will install the file into the windows.

 Some binary packages that Scrapy depends on (like Twisted, lxml and pyOpenSSL) require a compiler available to install, and fail if you don’t have Visual Studio installed. You can find Windows installers for those in the following links.




And its done. Now follow the scrapy tutorial and make spiders to crawl the websites. 
Happy Crawling

Tuesday, February 5, 2013

MULTIPLICATION AND DIVISION IN DJANGO TEMPLATES

Django only provides with the built-in add tag. It means if you have to subtract something you have to use the same add tag. Generally it is recommended that you should do maths operations in the views. but if you want to do it in templates then there are two ways
  1.  Write you own template tag that should receive arguments and return results. That is also easy you have to have a template tag directory in you apps and settings file. To find more on that follow this link.
  2. The other is to follow this post. It will let you know how to multiply and divide without creating your own template tags.
 Lets start with a simple add example.
{{ list.item |add:"10" }}
will return the result by adding item and 100
item + 10 is equivalent to {{ list.item |add:"10" }}
If you want to subtract then 
{{ list.item |add:"-10" }}
will return the result by adding -100 to item
item - 10 is equivalent to {{ list.item |add:"-10" }} 
Now comes the tricky part,  if you want to multiply or divide then???

Its easy. You need to take a look at the widthratio tag. It takes 3 arguments. Now you have to play around with this tag.
Normally it is like
{% widthratio X Y Z %}
How it is evaluated?
         It is evaluated like X/Y*Z. Now if you want to Multiply supply Y as 1 so it would be X/1 * Z that evaluates to X*Z. Similarly if you want to divide than supply Z as 1 it would evaluate to X/Y * 1 which has no effect on the result.
In short
To Compute A*B:
{% widthratio X 1 Z %}
To Compute A/B:

{% widthratio A B 1 %}
In templates you usually have lists upon which you are iterating or any other data structure. so you need to replace the variable with you variables or items and example of that would be
{% for list in temp_list %}
        {% widthratio list.price 1 list.books %} 
{% endfor %} 
This will multiply the price with the books by iterating over this list.

To demonstrate the combined use use of add and multiplication the example is demonstrated below:
compute (P+Q) * (R+S): {% widthratio P|add:Q 1 R|add:S %}









Monday, February 4, 2013

ITERATING OR DISPLAYING DICTIONARY ITEMS IN DJANGO TEMPLATES

Iterating over a dictionary in python templates is what we usually come across. In this section i have described how to iterate a dictionary and also what happens if its values are a tuple.

{% for key, val in dict.items %}
    <td>{{ key }}</td>
    <td>{{ val }}</td>
{%  endfor  %}

If the dictionary value contains a Tuple: 
For example if your dictionary is like

{'title' : ('book','play'), title2' : ('book2','play2')}

Then play with the indices of tuples
for instance the book, book2 and play,play2 are at indices 0 and 1 respectively, so we can access their values in templates like described under

 {% for key, val in dict.items %}
    <td>{{ key }}</td>
    <td>{{ val.0 }}</td>
    <td>{{ val.1 }}</td>
{%  endfor  %}
This will display the key and against the key the values of tuples

Now if you want to match a key by converting it in lowercase so use built-in template tag for this purpose
if you have a template variable name then it can be converted to lowercase by using lowerfilter
{{ name | lower }}
There are many built-in templates for django which can be found at
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs
You can also make your custom template tags. I will be publishing a post in near future guiding you about making the custom template tags