quiz/views.py
author nishanth
Tue, 20 Apr 2010 15:39:07 +0530
changeset 13 ad193c5014b2
parent 12 81cd0140a0f2
child 14 ea7d372bfbff
permissions -rw-r--r--
added ip field to model and used it in start page

from django.db import IntegrityError

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.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
    """

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

    try:
        Quiz.objects.get(user_ip=ip)
        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)