quiz/views.py
author nishanth
Tue, 20 Apr 2010 15:44:43 +0530
changeset 14 ea7d372bfbff
parent 13 ad193c5014b2
child 15 99af908a4174
permissions -rw-r--r--
implemented more constraints on the register for test page

from django.db import IntegrityError

from django.http import Http404

from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate

from django.shortcuts import redirect, render_to_response

from offline.event.models import Event

from offline.quiz.utils import gen_key
from offline.quiz.models import Profile

from offline.quiz.forms import UserRegisterForm

def start_page(request):
    """ first see if user is authenticated.
    If he is, redirect to the page where quiz happens.
    Else register the user
    """

    try:
        event = Event.objects.all()[0]
    except IndexError:
        raise Http404
    
    if event.quiz_status == '00':
        raise Http404

    user = request.user
    if user.is_authenticated():
        return redirect("/quiz/start/%s"%user.username)

    try:
        Quiz.objects.get(event=event,user_ip=ip,quiz_num=event.quiz_status)
        return redirect("/quiz/complete")
    except Quiz.DoesNotExist:
        pass

    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data

            while True:
                try:
                    username = gen_key(20)
                    new_user = User.objects.create_user(username, "temp@temp.com", "123")
                    break
                except IntegrityError:
                    pass

            new_user.first_name = data['first_name']
            new_user.last_name = data['last_name']
            new_user.save()

            new_profile = Profile(user=new_user)
            new_profile.profession = data['profession']
            new_profile.affiliated_to = data['affiliated_to']
            new_profile.save()

            user = authenticate(username=username, password="123")
            login(request, user)
            return redirect("/quiz/start/%s"%username)

        else:
            return render_to_response('register.html',{'form':form})
    else:
        form = UserRegisterForm()
        return render_to_response('register.html',{'form':form})

def start_quiz(request, username):
    logout(request)