Python Django

Django model queries

Django model (sql) queries

This is a dump data

posts =leaveRegister.objects.filter(status='') #.values()


geting releted joins

eg:-tables : User, leaveRegister, leaveType
    bs = leaveRegister.objects.all().select_related() #leaveType
    for b in bs:

    #posts = leaveRegister.objects.order_by('-pub_date')[:5]
    #cheese_blog = Blog.objects.get(name="Cheddar Talk")
    #posts = leaveRegister.objects.filter(status='' )
    #posts = leaveRegister.objects.get(status='' )
    posts =leaveRegister.objects.filter(status='') #.values()
    #claimed_opponents = User.objects.filter(gameclaim_opponent__me__user=claimer)


get user by id

u = User.objects.get(request.POST['profile_id'])
By bm on July 8, 2014 | Python Django | A comment?

Django how to get form values in views

    subject = request.POST.get('subject', '')
    message = request.POST.get('message', '')
    from_email = request.POST.get('from_email', '')
By bm on | Python Django | A comment?

Django send Email

from django.core.mail import send_mail

send_mail('Subject here', 'Here is the message.', '[email protected]',    ['[email protected]'], fail_silently=False)


email = EmailMessage('Hello', 'Body goes here', '[email protected]',
            ['[email protected]', '[email protected]'], ['[email protected]'],
            headers = {'Reply-To': '[email protected]'})


Html email

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")


Hello {{ username }} - your account is activated.


Hello <strong>{{ username }}</strong> - your account is activated.

By bm on | Python Django | A comment?

Django generating response output

Methord 1

    from django.http import HttpResponse
    from django.template import RequestContext, loader

    template = loader.get_template('hr/index.html')
    context = RequestContext(request, {'leaveRequests': leaveRequests,})  
    return HttpResponse(template.render(context))

Methord 2

    from django.shortcuts import render
    from django.http import HttpResponse

    response = HttpResponse()
    response = render(request, 'hr/index.html',{'leaveRequests': leaveRequests,})
    response.set_cookie(key='sampCookieKey', value=1)
    return response  

By bm on | Python Django | A comment?

Django user and group

Creating Group

from django.contrib.auth.models import Group

group = Group(name="GroupName")

Adding user in to group

g = Group.objects.get(name='GroupName') 


get user groups


for g in request.user.groups.all():

login required decorator and passes test

from django.contrib.auth.decorators import login_required, user_passes_test

def is_in_multiple_groups(user):
return user.groups.filter(name__in=['hr'])

@user_passes_test(is_in_multiple_groups, login_url='/login/')
def dashboard(request):
     #some code


By bm on | Python Django | A comment?

Django how to log a user In and Out

from django.contrib.auth import authenticate, login & logout

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login & logout(request, user)
            # Redirect to a success page.
            # Return a 'disabled account' error message
        # Return an 'invalid login & logout' error message.

def logout_view(request):


By bm on | Python Django | A comment?