Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Find the last friday using python datetime function

Posted In: . By Webdevelopmentlogics


from datetime import datetime, timedelta

def find_last_friday():     current_time = datetime.now()     last_friday = (         current_time.date()         - timedelta(days=current_time.weekday())         + timedelta(days=4, weeks=-1)     )     return last_friday


 


 import re

txt = """The rain in 


Spain"""

x = re.search("^The.*spain$", txt, flags=re.S|re.I)


if x:

  print("YES! We have a match!")

else:

  print("No match")


 


To install python with specific version in virtualenv use the following command
virtualenv --python=/usr/bin/python3.2 MyEnv

 

Using multiple model in django form

Posted In: , . By CreativeSolutions


 To use profile model with user form we need to initialize the form fields in the form. Then to get the values on edit we need to initialize __init__ function and passing the profile object from the view

 Ex: forms.py
 class SuperUserEditForm(forms.ModelForm):
    birthday = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False)
    phone_number = forms.CharField(max_length=100, required=False, label="Home Phone")
    cell_number = forms.CharField(max_length=100, required=False)
    carrier = forms.ChoiceField(choices=CARRIERS, required=False)
   
    def __init__(self, profile=None, *args, **kwargs):
        super(SuperUserEditForm, self).__init__(*args, **kwargs)
        if(profile):
            self.fields['cell_number'].initial = profile.cell_number
            self.fields['carrier'].initial = profile.carrier
            self.fields['birthday'].initial = profile.birthday
            self.fields['phone_number'].initial = profile.phone_number

 Ex: views.py
     form = SuperUserEditForm(profile=profile, instance=user)

     on POST
     form = SuperUserEditForm(data=request.POST, instance=user)

 

Csv upload and import in python django

Posted In: , . By CreativeSolutions


 if request.method == 'POST':
        srcfile = request.FILES.get("file", None)
        reader = csv.DictReader(srcfile) # read rows into a dictionary format
        for row in reader:
   print row

 

Get python django model choice in View

Posted In: , . By CreativeSolutions


Suppose you have a model

 class User(models.Model):

   TYPES = (
('Admin', 'Admin'),
('Staff', 'Staff'),
  )


 You can access this in the view using the following code

 In your view file

 from app.core.models import User

 def save(request):
     user_types = User.TYPES

    render('user/form.hrml', {user_types:user_types})

If you want to use this variable in the template, Assign that value user_types as a dictionary variable then use the below code
{% for value, text in user_types %}
{{ value }} {{ text }}
{% endfor %}


 

Django query with list of values in where clause

Posted In: , . By CreativeSolutions


If we need to fetch data like the MySQL IN clause, we can do it by using filter function with the list of values
user_ids= [1,2,3]
Ex. User.objects.filter(id__in = user_ids)

 


import time

Then add the below code
#Finding the daylight saving time
    is_dst = time.daylight and time.localtime().tm_isdst > 0
    utc_offset = (time.altzone if is_dst else time.timezone)
#Checking for negative and positve offset values
    if(utc_offset > 0):
        utc_offset_hours = (utc_offset / 3600)
        sign = '- '
    else:
        utc_offset_hours = (-(utc_offset) / 3600)
        sign = '+ '
    utc_offset_minutes =  (utc_offset % 3600) / 60
#Converting Integer values to string before concatenating
    utc_offset = sign + str(utc_offset_hours) + '.' +str(utc_offset_minutes)
    print utc_offset

 

Install new python package in virtualenv

Posted In: , . By Webdevelopmentlogics


  1. Enable virtualevn using command 'soure bin/activate'
  2. Then try the command 'echo $PATH' to show it's path. Then it will show the path with like given below
     /var/path/virtauanenv/bin
  3. Go the the package folder which you want to install. Then use the below command
     /home/user/package/folder$ /var/path/virtauanenv/bin/python setup.py install

 


To convert it uses the function eval
Ex:
  >>> lUnicodeData = u'[0,1,2]'
  >>> eval(lUnicodeData)
       [0, 1, 2]

 

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.

 

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