Skip to content

Commit

Permalink
Merge pull request #1 from jayesh92/master
Browse files Browse the repository at this point in the history
Admin Functionality
  • Loading branch information
rosariorobinson committed Jul 9, 2014
2 parents b0bf4ce + dd39d6a commit 0df8f41
Show file tree
Hide file tree
Showing 23 changed files with 926 additions and 0 deletions.
Binary file added AdminUnit/.DS_Store
Binary file not shown.
Binary file added AdminUnit/AdminUnit/.DS_Store
Binary file not shown.
Empty file added AdminUnit/AdminUnit/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions AdminUnit/AdminUnit/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.contrib import admin
from AdminUnit.models import UserProfile, Event, AssignedJob
from django.contrib.auth.models import User

admin.site.register(UserProfile)
admin.site.register(Event)
admin.site.register(AssignedJob)
88 changes: 88 additions & 0 deletions AdminUnit/AdminUnit/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from django import forms
from django.contrib.auth.models import User
from .models import UserProfile, Event, AssignedJob
from django.forms import ModelForm

class UserForm(forms.Form):
'''
As per the models, Registering a user involves two forms, user from auth models and custom-defines userprofile. This class is associated with forms for user table
from auth.
'''
firstname = forms.CharField(required=True)
lastname = forms.CharField(required=True)
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
password = forms.CharField(widget=forms.PasswordInput,required=True)
password2 = forms.CharField(widget=forms.PasswordInput, label="Confirm password", required=True)

# Check if both passwords are same
def clean_password2(self):
password = self.cleaned_data['password']
password2 = self.cleaned_data['password2']
if password != password2:
raise forms.ValidationError("Passwords do not match.")
return password2

# Check if this username is not already existing
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError('Username "%s" is already in use.' % username)


class UserProfileForm(forms.Form):
'''
As per the models, Registering a user involves two forms, user from auth models and custom-defined userProfile. This class is associated with forms for userProfile
table.
'''
address = forms.CharField(required=True)
location = forms.CharField(required=True)
state = forms.CharField(required=True)
organization = forms.CharField(required=True)
phone = forms.CharField(required=True)

# Check if both passwords are same
def clean_phone(self):
phone = self.cleaned_data['phone']
if len(phone)!=10:
raise forms.ValidationError("Invalid phone number.")
for i in range(10):
if phone[i].isalpha():
raise forms.ValidationError("Invalid phone number.")
return phone


class EventForm(ModelForm):
'''
Class Responsible for displaying forms of Event Class, inheriting ModelForm Class.
'''
class Meta:
model = Event

# To ensure noOfVolunteersRequired > 0
def clean_noOfVolunteersRequired(self):
noOfVolunteersRequired = self.cleaned_data['noOfVolunteersRequired']
print noOfVolunteersRequired
if noOfVolunteersRequired <= 0:
raise forms.ValidationError("Please input atleast one volunteer")
return noOfVolunteersRequired

# Check if this username is not already existing
def clean_eventName(self):
eventName = self.cleaned_data['eventName']
try:
Event.objects.get(eventName=eventName)
except Event.DoesNotExist:
return username
raise forms.ValidationError('Event Name "%s" is already in use.' % eventName)


class AssignJobsForm(ModelForm):
'''
Class Responsible for displaying forms of AssignedJob Class, inheriting ModelForm Class.
'''
class Meta:
model = AssignedJob
47 changes: 47 additions & 0 deletions AdminUnit/AdminUnit/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from django.db import models
from django.contrib.auth.models import User
from django.db.models import ForeignKey
from django import forms
import datetime

class UserProfile(models.Model):
'''
Model for UserProfile, each record is a one-to-one mapping ro user model from auth and also contains few other parameters
'''
user = models.OneToOneField(User)

address = models.CharField(max_length=128)
location = models.CharField(max_length=128)
state = models.CharField(max_length=128)
organization = models.CharField(max_length=128)
phone = models.CharField(max_length=128)

def __unicode__(self):
return self.user.username


class Event(models.Model):
'''
Model structure of Event Table
'''
eventName = models.CharField(max_length=128)
noOfVolunteersRequired = models.IntegerField()
startDate = models.DateTimeField()
endDate = models.DateTimeField()

def __unicode__(self):
return self.eventName


class AssignedJob(models.Model):
'''
Model structure for Jobs, each job has a many-to-one relationship with events, i.e., there can be 'n' number of jobs associated with one single event. 'event' is
therefore a foreign key
'''
event = models.ForeignKey(Event)

volunteerName = models.CharField(max_length=128)
job = models.CharField(max_length=128)

def __unicode__(self):
return self.event.eventName
3 changes: 3 additions & 0 deletions AdminUnit/AdminUnit/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
17 changes: 17 additions & 0 deletions AdminUnit/AdminUnit/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.conf.urls import patterns, url
from AdminUnit import views

urlpatterns = patterns('',
url(r'^$', views.index),
url(r'^register/$', views.register),
url(r'^event/$', views.editEvent),
url(r'^event/(?P<eventId>\d+)/$', views.editEvent),
url(r'^deleteEvent/(?P<eventId>\d+)/$', views.deleteEvent),
url(r'^allEvents/$', views.allEvents),
url(r'^assignJob/$', views.assignJob),
url(r'^assignJob/(?P<jobId>\d+)/$', views.assignJob),
url(r'^allAssignedJobs/$', views.allAssignedJobs),
url(r'^deleteJob/(?P<jobId>\d+)/$', views.deleteJob),
url(r'^login/$', views.login_process),
url(r'^logout/$', views.logout_process),
)
157 changes: 157 additions & 0 deletions AdminUnit/AdminUnit/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, render_to_response

from .forms import UserForm, UserProfileForm, EventForm, AssignJobsForm
from .models import UserProfile, Event, AssignedJob

def index(request):
'''
Controller for VMS Homepage
'''
return render(request,"AdminUnit/index.html")

def register(request):
'''
This method is used to register new user into the system as a volunteer
'''

# POST Request, submitted form has come as a request
if request.method == 'POST':
userForm = UserForm(request.POST)
userProfileForm = UserProfileForm(request.POST)

if userForm.is_valid() and userProfileForm.is_valid():
user = User.objects.create_user(first_name=userForm.cleaned_data['firstname'],last_name=userForm.cleaned_data['lastname'],
email=userForm.cleaned_data['email'],username=userForm.cleaned_data['username'],
password=userForm.cleaned_data['password'])

userProfile = UserProfile(user=user, address=userProfileForm.cleaned_data['address'],location=userProfileForm.cleaned_data['location'],
state=userProfileForm.cleaned_data['state'],organization=userProfileForm.cleaned_data['organization'],
phone=userProfileForm.cleaned_data['phone'])

userProfile.save()
return HttpResponse("You have registered, login available @ AdminUnit/")

# GET Request, render empty form
else:
userForm = UserForm()
userProfileForm = UserProfileForm()

return render(request, "AdminUnit/register.html",{ "userForm" : userForm , "userProfileForm" : userProfileForm })

def login_process(request):
'''
Authenticate a user against their credentials
'''

# POST Request, submitted form has come as a request, authenticate and redirect to apt page
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']

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

if user:
if user.is_active:
login(request,user)
return HttpResponse("You are logged in, logout available @ AdminUnit/")
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponse("Invalid login details supplied.")

# GET Request, display login form template
else:
return render(request,'AdminUnit/login.html')

@login_required
def logout_process(request):
'''
logout a user
'''
logout(request)
return HttpResponseRedirect('/AdminUnit/')

@login_required
def editEvent(request, eventId=None):
'''
Use to Edit/Create Event, In case of Creating new event eventId is None and therefore eventInstance
'''
if eventId:
eventInstance = Event.objects.get(pk=eventId)
else:
eventInstance = None

# POST Request, submitted form has come as a request. If eventInstance is none implies new record has to be saved else edited record
if request.method == 'POST':
eventForm = EventForm(request.POST,instance = eventInstance)
if eventForm.is_valid():
newRecord = eventForm.save()
return HttpResponse("Event Created/Edited")

# to handle a GET Request
else:
eventForm = EventForm(instance=eventInstance)

return render(request, "AdminUnit/event.html",{"eventForm" : eventForm})

@login_required
def assignJob(request,jobId=None):
'''
Controller to Edit/Create Jobs. In case of Creating new job, jobId is None and therefore jobInstance
'''
if jobId:
jobInstance = AssignedJob.objects.get(pk=jobId)
else:
jobInstance = None

# POST Request, submitted form has come as a request. If jobInstance is none implies new record has to be saved else edited record
if request.method == 'POST':
assignJobsForm = AssignJobsForm(request.POST, instance = jobInstance)
if assignJobsForm.is_valid():
newRecord = assignJobsForm.save();
return HttpResponse('Job Assigned')
else:
assignJobsForm = AssignJobsForm(instance = jobInstance)

return render(request, "AdminUnit/assign_jobs.html",{"assignJobsForm" : assignJobsForm})

@login_required
def allEvents(request):
'''
Controller responsible for displaying all Events that have been registered, alongside will be displayed the links to edit/delete an event
'''
allEvents = Event.objects.all()
return render(request, "AdminUnit/all_events.html", {"allEvents" : allEvents});

@login_required
def allAssignedJobs(request):
'''
Controller responsible for displaying jobs registered across all Events that have been registered, alongside will be displayed the links to edit/delete the same
'''
allAssignedJobs = AssignedJob.objects.all()
return render(request, "AdminUnit/all_assigned_jobs.html", {"allAssignedJobs" : allAssignedJobs});

@login_required
def deleteEvent(request,eventId=None):
'''
Delete's an event with a given primary key
'''
Event.objects.filter(pk=eventId).delete()
allEvents = Event.objects.all()
return render(request, "AdminUnit/all_events.html", {"allEvents" : allEvents});

@login_required
def deleteJob(request,jobId=None):
'''
Delete's a job with a given primary key
'''
AssignedJob.objects.filter(pk=jobId).delete()
allAssignedJobs = AssignedJob.objects.all()
return render(request, "AdminUnit/all_assigned_jobs.html", {"allAssignedJobs" : allAssignedJobs});

Empty file added AdminUnit/VMS/__init__.py
Empty file.
60 changes: 60 additions & 0 deletions AdminUnit/VMS/populate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os

def populate():
python_cat = add_cat('Python')

add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")

add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")

add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")

django_cat = add_cat("Django")

add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")

add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")

frame_cat = add_cat("Other Frameworks")

add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")

add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")

# Print out what we have added to the user.
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print "- {0} - {1}".format(str(c), str(p))

def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
return p

def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
return c

# Start execution here!
if __name__ == '__main__':
print "Starting AdminUnit population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'VMS.settings')
from AdminUnit.models import Category, Page
populate()
Loading

0 comments on commit 0df8f41

Please sign in to comment.