Friday, 24 June 2016

Two views inside one

It was some thing new for me- implementing two views inside one. In the administrator app in VMS, I used two views for report generation: one to display the form and other one to list the volunteer details. The following is the sample code that use single view that calls another two views.

class ShowReportListView(LoginRequiredMixin, ListView):
    template_name = "administrator/report.html"    
    organization_list = get_organizations_ordered_by_name()
    event_list = get_events_ordered_by_name()
    job_list = get_jobs_ordered_by_title()

    def post(self, request, *args, **kwargs):
        report_list = get_administrator_report(
            self.request.POST['first_name'],
            self.request.POST['last_name'],
            self.request.POST['organization'],
            self.request.POST['event_name'],
            self.request.POST['job_name'],
            self.request.POST['start_date'],
            self.request.POST['end_date'],
        )
        organization = self.request.POST['organization']
        event_name = self.request.POST['event_name']
        total_hours = calculate_total_report_hours(report_list)
        return render(request, 'administrator/report.html',
                      {'report_list': report_list, 
                      'total_hours': total_hours, 
                      'notification': True,
                      'organization_list': self.organization_list,                         
                      'selected_organization': organization,
                      'event_list': self.event_list,                                      
                      'selected_event': event_name, 
                      'job_list': self.job_list})

class GenerateReportView(LoginRequiredMixin, View):

    def get(self, request, *args, **kwargs):
        view = ShowFormView.as_view()
        return view(request, *args,**kwargs)

    def post(self, request, *args, **kwargs):
        view = ShowReportListView.as_view()

GenerateReportView calls ShowFormView that displays the form and ShowReportListView that list the volunteers.


Tuesday, 7 June 2016

Django's authentication system

Django's authentication system can serve the most common needs like handling wide range of tasks, implementation of passwords and permissions etc.

My second module of the GSoC project is the migration of authentication app to class based views. Authentication app used function based view for login and logout process earlier which was bit lengthy. The following was the function based view used for authentication purpose earlier.


auhentication/views.py
from authentication.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

def index(request):
    return HttpResponse("Hello world")
    
def login_process(request):

    if request.method == 'POST':

        authentication_form = AuthenticationForm(request.POST)

        if authentication_form.is_valid():
            username = request.POST.get('username')
            password = request.POST.get('password')

            user = authenticate(username=username, password=password)

            if user:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(reverse('home:index'))
                else:
                    return HttpResponse("Your account is disabled.")
            else:
                return render(request, 'authentication/login.html', {'authentication_form' : authentication_form, 'is_invalid_credentials' : True,})
        else:
            return render(request, 'authentication/login.html', {'authentication_form' : authentication_form,})
    else:
        return render(request, 'authentication/login.html', {'is_invalid_credentials' : False,})

@login_requireddef logout_process(request):

    logout(request)
    return HttpResponseRedirect(reverse('home:index')
authentication/urls.py
from django.conf.urls import patterns, url
from authentication import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^login/$', views.login_process, name='login_process'),
    url(r'^logout/$', views.logout_process, name='logout_process'),
)
It can be written in a simpler way using Django's built in auth views. The rewritten code for authentication is as follows.
Create a views.py in vms

vms/views.py
from django.shortcuts import redirect
from django.views.generic.edit import FormView
from django.core.mail import send_mail
from django.core.mail.message import BadHeaderError
from django.http.response import HttpResponse

from vms import settings

def anonymous_required(func):
    def as_view(request, *args, **kwargs):
        redirect_to = kwargs.get('next', settings.LOGIN_REDIRECT_URL )
        if request.user.is_authenticated():
            return redirect(redirect_to)
        response = func(request, *args, **kwargs)
        return response
    return as_view
anonymous_required is the conventional decorator that allows the programmer to restrict access to some views only to logged in users




vms/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
#from importlib._bootstrap import _NamespaceLoaderfrom vms.views import anonymous_required
from django.contrib.auth.decorators import login_required
import registration.views as views
from django.contrib.auth import views as auth_views

#admin.autodiscover()
urlpatterns = patterns('',
    url(r'^portal', TemplateView.as_view(template_name='home/home.html'),name='home'),
    url(r'^login/$',
        anonymous_required(auth_views.login),
        {'template_name': 'authentication/login.html'},
        name='login_process'),
    url(r'^user/logout/$',
        auth_views.logout,
        {'template_name': 'home/home.html'},
        name='logout_process'),
)
Assuming that you are done setting up built-in Django user authentication, add this in your settings.py. NOTE: 'home' here is the URL of the homepage. It will redirect the user to homepage once he is logged in. It is up to you what to replace it with.
vms/settings.py
LOGIN_URL = reverse_lazy('auth:user_login')
LOGIN_REDIRECT_URL = 'home'

Saturday, 7 May 2016

Migrating Volunteer Management System to Class based views- [GSoC-16 Project]

Volunteer Management System
Systers has many volunteers that offer their skills, time and commitment to accomplish their vision- Women in Computing. The community has implemented a Volunteer Management System to manage their volunteer contact information, track hours and events they worked, and provide reporting functionality at the least.
Django 1.3 introduced class-based views and also added a range of generic class-based views. From then, function-based views have been marked as deprecated. Most of the function-based views in the Systers VMS portal violates DRY.  Class-based generic views helps to streamline common use cases, saving development time and effort.

Migrating FBV to CBV
A view is a callable which takes a request and returns a response. This can be more than just a function in Django. Class-based views allows to structure our views and reuse code by harnessing inheritance and mixins.
One of the advantages of CBV is Inheritance. For instance, large projects like VMS has a lot of redundant code due the repetition of similar views. By migrating to CBV, views could be inherited and thus avoid code redundancy.

Few advantages, which VMS can achieve by migrating to Django’s class based views are :
  1. Django offers various generic views like CreateView, UpdateView, FormView, ListView and DetailView to handle views easily. For eg: Allow users to Create, Update and Delete events and shifts of volunteers with or without authorization, without violating DRY.
  1. Better code readability, reducing the number of lines of code, easing the code review process.
  2. Replacing the decorators by mixins instead, makes them more flexible, extensible and DRYer, just like the move from FBVs to CBVs.  
  3. Better handling of form data, which is handled in a traditional way in FBVs.
  4. Better support from the Django development community as the recent developments are CBV based.




Friday, 6 May 2016

Systers- A sisterhood

Systers is a forum for women who love computing. It's open for women of all ages who are into technical world. It was founded by Anita Borg with 12 other women as small mailing list. Then it grew up into a big team with the support and cooperation of other women.
The motto of the community is “increase the number of women in computer science and make the environments in which women work more conducive to their continued participation in the field.”


My experience with Systers
As an organization that take effort to bring more women into the world of computing, I am very proud to be a part of it. My relationship with Systers started as a GSoC-2016 intern. The community has always been so active with instant replies on Slack channel and showed keen interest in solving issues. They value even our small contribution very much.


I started with small bug fixes in Volunteer Management Sytem- a Django application that developed to manage the volunteers in Systers community. To get done with my first bug wasn’t easy. Struggled to understand the code base and documentation. Eventually, when the patch was merged and when I got to see the trivial contribution that I made, it was pure joy. And that’s how I started contributing to Systers.

Friday, 8 May 2015

Building a Sugar Desktop Environment

Clone the sugar-build repository from git
git clone git://github.com/sugarlabs/sugar-build.git

Enter in the directory and pull the latest source code
cd sugar-build
./osbuild pull

Build the source code
./osbuild shell
build

Finally run the Sugar environment
run

You will get your Sugar environment open if there is no error.


snapshot2.png



Type Shift-Alt-Q inside sugar to exit.

Friday, 6 February 2015

Sugar for Children


Sugar IDE
Sugar is an interactive and easy to learn platform for kids. And now, coming to what is Sugar? Sugar is a free and open source desktop environment designed for interactive learning for children. It started as a part of One Laptop per Child project (OLPC) as its default desktop environment. The mission of OLPC is to develop low cost laptops and provide children around the world with new opportunities. Sugar is a free software developed under Sugar Labs, which is a non-profit organization where developers and educationists work together for the development of the software. Sugar Labs is a community that supports and promotes Sugar learning platform.

Sugar is an attractive and colorful desktop environment created with an aim of quality education for children. Sugar does not use desktop, folder or window as its user interface objects. Instead, it uses a full screen view which helps children to concentrate on one job at a time. It is developed in Python language and runs on GNU/Linux. It is released under GNU General Public License and is available in 25 languages. Most applications in Sugar are the forks of existing applications in GNOME. It is available as USB-Bootable Linux distribution and Live CDs.

Why Sugar is interesting? 
Sugar supports sharing and collaboration for users. It does not contain applications like other desktop environments. Learner applications in Sugar are called Activities. It includes activities like Pippy(introductory environment to learn Python), Journals(object and activity browsing), Distance(measure the distance between two laptops) etc which are exclusively designed for easy use for kids. In the Sugar Neighborhood view, children see their connected friends; they can join each other’s activities.

Sugar teaches you through three experiences:

Sharing, which shows the presence of others involved in the activity by sharing ideas.

Reflecting, where Sugar uses journals to record each activity of the user which helps in progress assessment.

Discovering, where users of different levels of skills join together in a single platform and go deeper and deeper with no restrictions.

Sugar provides children with the opportunity to explore, express and experiment themselves. 

References 








 


Friday, 9 January 2015

Writing a simple Linux Device Driver

          A device driver is a program that controls a particular type of device that is attached to your computer. There are device drivers for printers, displays, CD-ROM readers, diskette drives, and so on.
Now let us write a simple Hello World driver code.
Create a directory anywhere in your home folder and navigate into that directory.
mkdir hello
cd hello
Create two files hello.c and Makefile
You can use any editor as you wish. Here I use Kate.
kate hello.c
Type the following code

#include <linux/init.h>
#include <linux/module.h>
static int __init hello_init (void) {
printk(KERN_ALERT "Hello World!!!");
return 0;
}
static int __exit hello_exit(void) {
printk(KERN_ALERT "Goodbye World!!!");
return 0;
}
module_init(hello_init);
module_exit(hello_exit);

Here, the hello_init() function runs when the module is loaded and hello_exit() funtion runs when the module is unloaded. Save the code.
Next we can create the Makefile.
kate Makefile
Type the follwing code in it. Make sure that you intent the code perfectly.


ifneq ($(KERNELRELEASE),)
obj-m := hello.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
    rm -rf *.o *.ko *.mod.*
endif


When you are done till here, we need to build the module. For that type,
make
It hardly takes half a minute. When the module is successflly built, you get a bunch of object files in the hello directory. Thus the Hello World module is ready.
Now let's see the working of the module by loading it into the kernel. Type,
sudo insmod hello.ko
This will load the module into the kernel which we can check by typing ,
lsmod
You get a list of module on top you get your hello module. To see whether the module is running in you kernel or not, type
dmesg
The Hello World message will be printed that we wrote in hello.c file
To remove the module type the following instruction in the terminal
sudo rmmod hello
Here the exit function that we typed in hello.c is run. To check the output type,
dmesg