Wednesday 25 December 2013

public and private objects into python


Python does not support privacy directly . Programmer need to know when it is safe to modify attribute from outside but anyway with python you can achieve something like private with little tricks.
wow this is awesome .

Now let's see a person can put anything private to it or not :P
class Person(object):
  
    def __priva(self):
        print "I am Private"
   
    def publ(self):
        print " I am public"
   
    def callpriva(self):
        self.__priva()



Now When we will execute :
>>> p = Person()
>>> p.publ()
 I am public
>>> p.__priva()
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    p.__priva()
AttributeError: 'Person' object has no attribute '__priva'

Explanation   : You can see  here we are not able to fetch that private method directly.

>>> p.callpriva()
I am Private
Explanation  : Here we can access private method inside class​


​Then how someone can access that variable  ???


You can do like :
>>>p._Person__priva
I am Private

​ wow ,  actually if python is getting any variable starting with  double underscore are “translated” by adding a single underscore and the class name to the beginning:

Note : If you do not want this name changing but you still want to send a signal for other  objects to stay away, you can use a single initial underscore names with an initial underscore aren’t imported with starred imports (from module import *)
Finally  : Python doesn’t really have an equivalent privacy support, although single
and double initial underscores do to some extent give you two levels of privacy

Friday 27 September 2013

send fake email using python smtplib library


Hi All,

Today we will learn how can we send a fake email from any email account using python .

we are using python library smtplib which will call machine's smtp server and it will send email from provided From email .
While using ubuntu you can use postfix as smtp server .


import smtplib
To ="91prashantgaur@gmail.com"
Subject = "Test Fake Email "
Message  = "Hi How are you  ?"
Email = 'test@gmail.com'            # from this email id we will send email 
server = smtplib.SMTP('localhost')        # local smtp server of machine
Message = string.join(("From: %s" % Email,
                                   "To: %s" % To,
                                   "Subject: %s" % Subject,
                                  "",
                                  Message
                                  ),"\r\n")
server.sendmail(Email , [To], Message)
server.quit()

If any question let me know at  91prashantgaur@gmail.com


Prashant Gaur
Python/JavaScript Developer
9717353657

Friday 23 August 2013

Block any particular IP address in django


in settings.py file ..

   BLOCKED_IPS = ('127.0.0.1',)    --- > touple of ip addressed

and in our view just simple  ---- >



    from django.conf import settings
    from django import http
    if request.META['REMOTE_ADDR'] in settings.BLOCKED_IPS:
          return http.HttpResponseForbidden('<h1>Forbidden</h1>')
    return render_to_response("home-page.html")

Wednesday 21 August 2013

how to use __in with __startswith in django queryset

Hi All,

Today we will see the code which will help us to use __in  with __startswith or any other filter.

First we will learn use of __in .

__in   ----> it is used to filter data from a list

namelist = ['sachin', 'dravid', 'dhoni', 'khan']
Player.objects.filter(name__in=namelist)                                                                          

Use of __startswith or __endswith to filter data based on starting ,ending pattern in any string .
Player.objects.filter(name__startswith='sac')

if you want to filter query where name will start with words given in any list you will use.


from django.db.models import Q
def startwithin(namelist):
        q = Q()
        for names in namelist:
            q |= Q(name__startswith=names)    # | will union all objects 
        return Player.objects.filter(q)
     


Thanks
Prashant Gaur

Tuesday 16 July 2013

Display AutoField(primary_key) as read only in Django admin

Generally It doesn't have an ID until you save it.


Please follow below code it will sure help you to overcome from None.

models.py
class A(models.Model):
    a = models.AutoField(primary_key=True)
   
    def __str__(self):
        return str(self.a)

admin.py 
class AAdmin(admin.ModelAdmin):
    list_display = ['a']
    readonly_fields = ['ass']

    def ass(self, obj):
        if obj.a is None:
            a = A.objects.all().order_by('-a')[:1]
            print a
            if a:
                return a[0].a + 1
            else:
                return 0
        else:
            return obj.a
admin.site.register(A, AAdmin)



Please check above code .if any issue please revert me.


Prashant Gaur
+91 9030015491

Friday 17 May 2013

Hack Django Admin , admin login after checking ip address

HI Friends ,
Today i will tell you how can we filter login of Admin user in respect of IP addresses stored in backend.
Work Motivation : Allow any admin user login only with any number of  ip address selected in backend .

Coding

we will create two models in models.py Profile , Failed


Profile :

class Profile(models.Model):
     user = models.ForeignKey(User)
     ip=models.IPAddressField(null=True)
     def __str__(self):
         return "%s's profile" % self.user

def create_user_profile(sender, instance, created, **kwargs):
     if created:
         profile, created = Profile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)

class Failed(models.Model):
     user=models.ForeignKey(User)
     timestamp=models.DateTimeField(auto_now_add=True)
     ip=models.IPAddressField()

Now Create a decorator
from django.http import HttpResponse
from django.contrib.auth.views import logout
from django.contrib.admin.models import User
from userapp.models import UserProfile , Failedlogintry

def check_ip_required(f):
     def wrap(request, *args, **kwargs):
         #it will check session of admin user , if session key exist then it will allow further else will redirect to login page
         try:
         #check admin user exists or not
             user=User.objects.get(username=request.user)
             #fetch user profile obj
             userprofileobj = Profile.objects.filter(user=user)
             iplist =[]
             for i in userprofileobj:
                 iplist.append(str(i.ip))
             #ip list is having all  ip address of that admin stored in backend
             loginip=str(request.META['REMOTE_ADDR'])
             if len(iplist) is 0: # if admin is not having any ip stored in backend
                 logout(request) # logout session of admin user
                 Failed.objects.create(user=user,\                                                ip=request.META['REMOTE_ADDR']) # make a entry in failedlogintry table
                 return HttpResponse("You are not authorized to Logins.")

             if loginip not in iplist:
                 logout(request) #if ip address from which admin is trying to login is not in db then logout
                 Failed.objects.create(user=user,\ ip=request.META['REMOTE_ADDR'])
                 return HttpResponse("You are not authorized to Login.")
         except:
                 pass
     return f(request, *args, **kwargs)

wrap.__doc__=f.__doc__
wrap.__name__=f.__name__
return wrap



admin.py
we can restrict any admin having only 10 ip in admin.py file
from django.contrib import admin
from userapp.models import UserProfile

class ProfileAdmin(admin.ModelAdmin):
     list_display=['user','ip']
     def save_model(self, request, obj, form, change):
          adminname = obj.user
          count = Profile.objects.filter(user=adminname).count()
          if count <= 9:
               obj.save()
         else:
               pass
admin.site.register(Profile, ProfileAdmin)





urls.py from userapp.decorators import decorated_includes, check_ip_required
url(r'^admin/',decorated_includes(check_ip_required , include(admin.site.urls)) ),

Please ignore indentation errors .if any issue please leave comment or mail me . Thanks & Regards:
Prashant Gaur
+91 9030015491
91prashantgaur@gmail.com

Saturday 4 May 2013

design a deque function in javascript

 
function Deque()
{
 this.stac=new Array();  
 this.popback=function(){ 
  return this.stac.pop(); 
 }
 this.pushback=function(item){
  this.stac.push(item);
 }
 this.popfront=function(){
  return this.stac.shift();
 }
 this.pushfront=function(item){
  this.stac.unshift(item);
 }
}
 
  
 
//push is function of Array in javascript to enter variable in last index of array.
//pop is function of Array in javascript to remove last variable from array.
//shift is use to add element in start of the array .
//unshift is use to remove element from start of the array .


function implementation {
 
var deque=new Deque();
deque.pushfront("Prashant");
deque.pushfront("Gaur");
deque.pushback("Deepak");
alert(deque.popfront());
alert(deque.popback()); 
alert(deque.popback()); 
alert(deque.popback()); 

 
}



You can design function for Queue  also only by using pop and unshift . :)




Thanks & Regards :
Prashant Gaur
+91 9030015491
91prashantgaur@gmail.com




 

Friday 26 April 2013

Hack django admin tricks : 1

We can hide checkbox dispayed in django admin model templates

It's very simple hack u just go to ur admin.py file's respective class:
class Player(admin.ModelAdmin):
    list_display = ['gamename,'gametype]
    actions=None




Regards:
Prashant Gaur
+91 9030015491
91prashantgaur@gmail.com
Hyderabad

Saturday 20 April 2013

Cool django admin tricks


1 ) Disable Add button in django admin interface for some models if they are having data in that table .


Answer :
Add below function in admin.py file in your respective class .

def has_add_permission(self,request):
        count = Data.objects.all().count()
        if count > 0:
            return False
        else:
            return True

2 ) disable delete operation for some models in django admin interface.

def has_delete_permission(self, request, obj=None):
        return False
 
 
 
 
3 ) Add link in django admin Interface .
 
list_display = ['my_url_field']   
    def my_url_field(self, obj):
        return '<a href="%s%s">%s</a>' % ('', obj.id, 'Click Here')
    my_url_field.allow_tags = True
    my_url_field.short_description = 'Data'
     

Saturday 16 March 2013

send email when django admin is created

 
 
from django.db.models.signals import post_save
from django.contrib.auth.models import User

def send_user_email(sender, instance=None, **kwargs):
    if kwargs['created']:
        #your code here to send mail 
 
post_save.connect(send_user_email, sender=User)

Monday 18 February 2013

Multilingual support in Django

  1. Go to settings.py file and
    USE_I18N = True
    USE_L10N = True
    Go to middleware_classes section
    add "'django.middleware.locale.LocaleMiddleware"
  2. Create Template and write code
    {%load i18n %}
    {% trans "Hi I am Prashant Gaur" %}  (you need to put all data in trans or any django template block)
  3. Create language files:
    go to project directory-
    mkdir locale
    django-admin.py makemessages -l en      (english
    django-admin.py makemessages -l sv       (swedish)   
    If you are getting any error so it means you are missing xgettext (ubuntu)
    sudo apt-get install gettext
  4. python manage.py compilemessages
  5. Now change language in browser to swedish it will automatically convert into swedish .
  6. You can create many language files and multilingual environment is ready
     

add custom link href in django admin interface

Hi :)
step1 ) first go to your app folder and them select admin.py file
step 2 ) now
class Player(admin.ModelAdmin):     
    list_display =['id','Name','Mail','Facebook_link']
    def facebook_link(self,obj):
        return '<a href="%s">Facebook</a>'%('http://www.facebook.com')
    facebook_link.allow_tags = True
    facebook_link.short_dscription = "Facebook"


Wednesday 13 February 2013

find result after passing list in filter query in django

Like You have a Table Student with column "name"
so if you need to filter your object based in given list with some names .


Answer :

namelist =['first','second','third','fourth']
obj = Student.objects.filter(name__in=namelist)