django学習個人総括のクッキーを削除に保存


ろんり
登録
ログイン---index---logout
views.py
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from models import User
class UserForm(forms.Form):
        username = forms.CharField()
        password = forms.CharField(widget=forms.PasswordInput)
def regist(req):                         # 
        if req.method == 'POST':
                uf = UserForm(req.POST)
                if uf.is_valid():
                        username = uf.cleaned_data['username']
                        password = uf.cleaned_data['password']
                        User.objects.create(username = username ,password = password)
                        print username,password
                        return HttpResponseRedirect('/login/')   # 
        else:
                uf = UserForm()
        return render_to_response('regist.html',{'uf':uf})
def login(req):                           # 
        if req.method == 'POST':
                uf = UserForm(req.POST)
                if uf.is_valid():
                        username = uf.cleaned_data['username']
                        password = uf.cleaned_data['password']
                        users = User.objects.filter(username = username ,password = password)       # , users , 
                        if users:
                                response = HttpResponseRedirect('/index/')
                                # response cookie,cookie 
                                response.set_cookie('username',username,3600)
                                return response     # username 
                        else:
                                return HttpResponseRedirect('/login/')
        else:
                uf = UserForm()
        return render_to_response('login.html',{'uf':uf})
def index(req):
        username = req.COOKIES.get('username','')   # cookie
        return render_to_response('index.html',{'username':username})
def logout(req):
        response = HttpResponse('logout')
        response.delete_cookie('username')
        return response

models.py
from django.db import models
class User(models.Model):
        username = models.CharField(max_length=20)
        password = models.CharField(max_length=200)
        def __unicode__(self):
                return self.username

templates/regist.html




       

        {{uf.as_p}}
       
       



templates/index.html




       

               

welcome {{username}}


                logout
       



templates/login.html




       

        {{uf.as_p}}
       
       



urls.py
    url(r'^admin/', include(admin.site.urls)),
    url(r'^regist/$','blog.views.regist'),
    url(r'^login/$','blog.views.login'),
    url(r'^index/$','blog.views.index'),
    url(r'^logout/$','blog.views.logout'),