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