MySQL query with left join and Date checking

Posted In: . By CreativeSolutions


SELECT p . *, l.lv_Date
FROM `people` AS p LEFT JOIN `leave` AS l
ON p.pl_Personid = l.lv_Tutor
WHERE p.pl_Usertype = 2 AND IF(l.lv_Date != NULL, l.lv_Date Not in ('2012-5-27'), NULL)

 







 The below code can be used to count the number of male/female in the Profile

 Profile.objects.values('gender').annotate(gener_count=Count('gender'))

 

Python - Convert unicde list to string

Posted In: . By CreativeSolutions


 import ast
 //data is the uncode list like u"[u'1', u'2', u'3', u'4']"
 s =  [ item.encode('ascii') for item in ast.literal_eval(data) ]
 val = ', '.join(s)

 If we try to convert to string using the join function it will not work and it will combine all the characters in the string. so we need to use the ast eval function with ascii encoding.

 


class MyForm(forms.ModelForm):
    OPTIONS = (
        ("IN", "India"),
        ("US", "United States"),
          )
    countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label = "Select Medications", choices=OPTIONS)
#To change the order use the below code
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = ['name', 'countries', 'states']

    class Meta:
            model = MyModel

 

Python - Convert list to String

Posted In: . By CreativeSolutions


 First, if it is a list of strings, you may simply use join this way:

 >>> mylist = ['elegant', 'kerala', 'package']
 >>> print ', '.join(mylist)
     Then the output will be as in below. If you need to print in separate line you can use the '\n' instead of  ', '
     elegant, kerala, package

 

How to use group by clause to fetch related data

Posted In: . By CreativeSolutions


There is no exact group by clause and we can use the function annotate to get the count of records with grouping data.

   If we need to fetch the related data from 2 tables,
    first we need to fetch the unique data from first table
    then we can use the filter function with id__in

  ex:    
    mapdata = MedicationMapping.objects.all()
    meds = Medication.objects.filter(id__in=mapdata)

 


LOAD DATA LOCAL INFILE 'file-path/file_name.csv' INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'

For more details
  http://dev.mysql.com/doc/refman/5.1/en/load-data.html



 

How to do add pagination in django framework

Posted In: . By Webdevelopmentlogics


In views.py add the below code
  d = FlatPage.objects.all() // Flatpage is the Model class
    paginator = Paginator(d, 2) # Show 2 help on each row
    page = request.GET.get('page')
   
    try:
        helps = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        helps = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        helps = paginator.page(paginator.num_pages)
    return render_to_response("flatpages_plus/list.html",{
            "data": helps }, RequestContext(request),
        )

In the template add teh following code

 div class="pagination"
         

                {% if data.has_previous %}
                 
  • previous

  •             {% endif %}
                {% if data.page_range_data.show_first %}
                 
  • 1

  •             {% endif %}
                {% for i in data.page_range_data.page_range %}
                    {% ifequal i data.number %}
                        {{ i }}
                    {% else %}
                       
  • {{ i }}

  •                 {% endifequal %}
                {% endfor %}
                {% if data.page_range_data.show_last %}
                   
  • {{ data.paginator.num_pages }}

  •             {% endif %}
                {% if data.has_next %}
                   
  • next

  •             {% endif %}
               

        /div

 

helpful links to learn django forms

Posted In: . By CreativeSolutions
 


1. Install virtualenv by dowloading or using the command 'yum install virtualenv' in terminal
 2. Then in the project's folder, run the command
     virtualenv [name] ex: venv
    with this you can add -no-site-packages or other options
 3. Then install django and necessary module in it.
 4. from the 'venv' directory created on executing the command 'virtualenv'
    run the command 'source bin/activate' in terminal
 5. run the command 'deactivate' from terminal to exit

 

How to set and print views variables in template

Posted In: . By CreativeSolutions


In the view
    return render(request, 'admin/user/form.html', {'form': form,'error_msg': error_msg})
In the template
    form action="" method="post">{{ form.as_p }}
    input type="submit" value="Save" /
    /form
    {% if error_msg %}
        {{ error_msg }}
    {% endif %}

 

Common field types in django models

Posted In: . By CreativeSolutions


OneToOneField
    - models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)(SET_NULL, SET_DEFAULT)
ManyToManyField
    - models.ManyToManyField(Group, related_name='profiles', blank=True, null=True)
    - models.ForeignKey(User, related_name='+', on_delete=models.CASCADE) - no backward relation on setting related_name to +
CharField
    - CharField(max_length=100, blank=True, null=True, choices=CARRIER_CHOICES, default=CARRIER_CHOICES[-1][0])
    -
EmailField
    - models.EmailField(max_length=255, blank=True, null=True)
ImageField
    - models.ImageField(blank=True, null=True, upload_to=settings.UPLOAD_ROOT)
DateField
    - models.DateField(blank=True, null=True)
    - models.DateTimeField(auto_now_add=True)  - for saving new date
    - models.DateTimeField(auto_now=True) - for last modified time
    - models.TimeField()
URLField
    - models.URLField(max_length=255, blank=True, null=True)
BooleanField   
    - models.BooleanField(default=True)
IntegerField   
    - models.IntegerField(default=0)   

 

Set not null validation in django form

Posted In: . By CreativeSolutions





To set the not null validation, we need to set the 'Blank=False' in the corresponding field declaration in model
 
  Ex:
      name = models.CharField(max_length=255, blank=False, null=True)
     
      In this null=True refers to the database property

 


Instructions:

    Step 1: FreeTDS
        Download FreeTDS
        Unpack the tarball
        $]cd freetds-VERSION (where version is the FreeTDS version number)
        $]./configure --prefix=/usr/local/freetds --enable-msdblib
        $]make
        $]su root
        $]make install
        $]make clean
    Step 2: SQL Server PHP extension
        Download the source for the right version of PHP (http://php.net/downloads)
        Unpack the tarball
        $]cd php-VERSION/ext (where VERSION is the PHP version number)
        Copy the mssql/ directory to someplace where you can compile it from
        CD to that directory
        $]phpize (this requires the php-devel package)
        $]./configure --with-mssql=/usr/local/freetds
        $]make
        $]su root
        $]make install
        $]make clean
       
        If php is already installed and mssql not added follow run the below command
        $yum install php-mssql
       
       
    Step 3: FreeTDS configuration
        $]vi /etc/freetds.conf (any editor available can used for this)
        Go to the end of the file
        Add the following lines
        ;--- Custom MSSQL server name ---
        ; THIS CAN BE ANY NAMED SERVER REFERENCE YOU WANT TO CREATE
        [SERVERNAME]
        ; This is the host name of the MSSQL server
        host=HOSTNAME
        ; This is the port number to use
        port=PORTNUMBER
        ; This is the TDS version to use for anything over Server 2000
        tds version=8.0
        Save the file and exit
        $]vi /etc/ld.so.conf (Again, any editor should be able to do this)
        Go to the end of the file
        Add the following line:
        /usr/local/freetds/lib
        Save the file and exit
    Step 4: Enabling MSSQL PHP extension
        $]cd /etc/php.d
        If there is no file named mssql.ini create one
        Edit the file and enter the following lines if not already there
        ; Enable mssql extension module
        extension=mssql.so
        Save the file and exit
    Step 5: Apache (This should be done any time PHP changes)
        $]/etc/rc.d/init.d/httpd stop
        $]/etc/rc.d/init.d/httpd start
        NOTE: $]apachectl -k graceful might work as well, though httpd start offers a status flag
    Step 6: Test a file at the CLI and at the Web Server


I used the below code and got the result "Version: Microsoft SQL Server 2005 - 9.00.5000.00 (Intel X86) Dec 10 2010 10:56:29 Copyright (c) 1988-2005 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)"
< ?php
$server = 'wic018q.server-sql.com:4656';

// Connect to MSSQL
$link = mssql_connect($server, 'vs328460_1_dbo', 'Uq9y6hz3QX');

if (!$link) {
die('Something went wrong while connecting to MSSQL'.mssql_get_last_message());
}

$version = mssql_query('SELECT @@VERSION');
$row = mssql_fetch_array($version);

echo "
Version: ".$row[0];

// Clean up
mssql_free_result($version);
? >

 Please visist the below url for more details
  http://www.robert-gonzalez.com/2008/03/31/connecting-php-on-linux-to-mssql-on-windows/

 

How to debug sql query in django

Posted In: . By Webdevelopmentlogics


  We can debug the django query using the 'print' command and look the terminal wher you alrady run the command 'python manange.py runserver'
  Ex:
       destination = Destination.objects.get(id = destId)
     print destination

 


To set the static folder path we need to edit the STATICFILES_DIRS variable in settings.py. Better to set the BASE_PATH+'/static' as the static folder.
  To set the BASE_PATH use the following code
   import os
       BASE_PATH = os.path.dirname(os.path.abspath(__file__))

 


To show the field name instead of Model object, define the below function in your model class

def __unicode__(self):
        return  u'%s' % (self.name)

where 'name' is one of the class attribute

 


While trying the django http://127.0.0.1:8000/admin/ url you may get the the Exception "Site matching query does not exist"

    I got it fixed by removing the django.contrib.sites from settings.py file.

 

Compile all django or python files

Posted In: . By Webdevelopmentlogics


python -m compileall path/to/project

 

How to find the django version

Posted In: . By Webdevelopmentlogics


First we need to enter into the python promt.
Then
>> import django
>> django.get_version()

 


It's because the verification missing in the form and need to add {% csrf_token %} inside form tag

 


This error comes because you have not imported the calling object. Please import everyting from class and try
 Ex: from MyClass import *

 


 This error may occur while creating a new project. The following can be any of the reason for this
 
  1. Check django installed properly, and check the folder site-packages in python installed folder.
  2. There can be issue with setting the PATH to the django folder and this can be solved by giving the full path
       Ex: /usr/lib/python2.7/site-packages/django/bin/django-admin.py startproject mysite
  3. This script should not execute from the python console. Go to the directory where you want to save the project then execute the command django-admin.py startproject mysite