天天看点

Django笔记-登陆注册-1

1、项目结构(eclipse+PyDev工具)(粘上来后代码缩进格式没有了,就先不整了)

Django笔记-登陆注册-1

2、关键代码:

test_log03.settings.py

INSTALLED_APPS = (

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'blog',

)

MIDDLEWARE_CLASSES = (

'django.contrib.sessions.middleware.SessionMiddleware',

'django.middleware.common.CommonMiddleware',

#'django.middleware.csrf.CsrfViewMiddleware',                  #注意把这里注释掉(CSRF)

'django.contrib.auth.middleware.AuthenticationMiddleware',

'django.contrib.messages.middleware.MessageMiddleware',

'django.middleware.clickjacking.XFrameOptionsMiddleware',

)

 #注意同步数据库,生成表格后才能在后期录入数据

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'test03',

'HOST':'localhost',

'PORT':'3306',

'USER':'root',

'PASSWORD':'passwd',

}

}

test_log03.urls.py

<body>

<center><h1>hello,register!</h1></center>

<!--注意post方法-->

<form method="post" >

{{uf.as_p}}

<input type="submit" value="OK"/>

</form>

</body>

blog.models.py

from django.db import models

class User(models.Model):

   username = models.CharField(max_length=20)

   password = models.CharField(max_length=30)

   def __unicode__(self):

       return self.username

blog.views.py

from django.shortcuts import render, render_to_response

from django import forms

from django.http import HttpResponse

from blog.models import User

class UserForm(forms.Form):

   username = forms.CharField()

   password = forms.CharField()

def register(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()

        user.username = username

        user.password = password

       user.save()

      print username,password

      return HttpResponse('ok')

else :

   uf = UserForm()

   return render_to_response('register.html',{'uf':uf})

转载于:https://www.cnblogs.com/chinas/p/4374977.html