Source

barcamp malacca / example / exampleapp / views.py

from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
# Create your views here.
from models import *

@login_required
def example_view(request):
    if request.method == 'POST':
        data = Example(name = request.POST.get('posting'),score = 0)
        data.save()
    res = Example.objects.all() 
    return render_to_response('example/template.html',{'res':res})
    
def example_register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        user = User.objects.create_user(username,email,password)
        user.save()
        return HttpResponseRedirect('/example/login/')
    else:
        return render_to_response('example/register.html',{})
        
def example_login(request):
    if request.method == 'POST': 
        username_ = request.POST.get('username')
        password_ = request.POST.get('password')
        user = authenticate(username = username_,password = password_)
        if user is not None:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect('/example/')
            else:
                return HttpResponseRedirect('/example/login/')
        else:
            return HttpResponseRedirect('/example/login/')
    else:
        return render_to_response('example/login.html',{})


def example_logout(request):
    logout(request)
    return HttpResponseRedirect('/example/login/')

@login_required
def example_like(request,id):
    data = Example.objects.get(id=id)
    data.score = data.score + 1
    data.save()
    return HttpResponseRedirect('/example/')

@login_required
def example_hate(request,id):
    data = Example.objects.get(id=id)
    data.score = data.score - 1
    data.save()
    return HttpResponseRedirect('/example/')