Django 로그인, 등록, 종료

16434 단어 django
주석 작성: 항목 만들기:
1. 프로젝트 만들기
django-admin startproject form_test
2. 응용 프로그램 만들기
1、cd form_test 2、sudo ./manage.py startapp form_app
셋째, 설정 응용
1、vim setting.py2, INSTALLEDAPPS 새로 만든 응용 프로그램 추가("form app")
4. URL(form test/urls.py) 만들기
#form_test/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'form_test.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'form_app.views.login',name='login'),
    url(r'^login/$', 'form_app.views.login',name='login'),
    url(r'^regist/$', 'form_app.views.regist',name='regist'),
    url(r'^index/$', 'form_app.views.index',name='index'),
    url(r'^logout/$', 'form_app.views.logout',name='logout'),
    url(r'^share/$', 'form_app.views.share',name='share'),
)

5. 데이터베이스 객체 만들기(form app/models.py)
from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length=50)
    password = models.CharField(max_length=50)

    def __unicode__(self):
        return self.username

6. 뷰 작성(/form app/views.py)
#coding:utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from models import User
# Create your views here.

#  
class UserForm(forms.Form):
    username = forms.CharField(label='   ',max_length=100)
    password = forms.CharField(label=' __ ',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.get_or_create(username = username,password = password)
            registAdd = User.objects.get_or_create(username = username,password = password)[1]
            if registAdd == False:
                #return HttpResponseRedirect('/share/')
                return render_to_response('share.html',{'registAdd':registAdd,'username':username})
            else:
                return render_to_response('share.html',{'registAdd':registAdd})

    else:
        uf = UserForm()
    return render_to_response('regist.html',{'uf':uf},context_instance=RequestContext(req))

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']
            #               
            user = User.objects.filter(username__exact = username,password__exact = password)
            if user:
                #    ,  index
                response = HttpResponseRedirect('/index/')
                # username     cookie,     3600
                response.set_cookie('username',username,3600)
                return response
            else:
                return HttpResponseRedirect('/login/')
    else:
        uf = UserForm()
    return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
#    
def index(req):
    username = req.COOKIES.get('username','')
    return render_to_response('index.html',{'username':username})
#    

def logout(req):
    response = HttpResponse('logout!!!')
    #  cookie    username
    response.delete_cookie('username')
    return response

def share(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']

            return render_to_response('share.html',{'username':username})
    else:
        uf = UserForm()
    return render_to_response('share.html',{'uf':uf})

7.templates(form app/templates) 만들기
1、cd templates 2、sudo touch share.html、regist.html、login.html、logout.html、index.html 3、share.html
{{registAdd}} <br> ================== <br> {% if username %}     {{username}}    <a href="http://127.0.0.1:8000/regist">  </a> {% else %}<a href="http://127.0.0.1:8000/login">  </a> {% endif %}

4、regist.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Regist</title> </head> <body> <h1>    </h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{uf.as_p}} <input type="submit" value="ok"></input> </form> <a href="http://127.0.0.1:8000/login">  </a> </body> </html>

5、login.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Login</title> </head> <body> <h1>    </h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{uf.as_p}} <input type="submit" value="ok"></input> </form> <a href="http://127.0.0.1:8000/regist">  </a> </body> </html>

6、index.html
<!DOCTYPE html> <html> <head> <title>index</title> </head> <body> <h1>Welcome {{ username }}!</h1> <br> <a href="http://127.0.0.1:8000/logout">  </a> </body> </html>

좋은 웹페이지 즐겨찾기