django做简单的用户登录和增删改查

本人是用eclipse做的,环境是python2.7、django1.9.13,创建完项目后在cmd启动一个app,python manage.py startapp  login,这个命令如果说没有就创建这个application

1.在settings.py

配置数据库

DATABASES = {

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test_cgd',
        'HOST':'127.0.0.1',
        'PORT':'3306',
        'USER':'root',
        'PASSWORD':'123456',
    }

}

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'login', #添加应用

)

在views.py中编写主要逻辑代码

# -*- coding: utf-8 -*- 
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from models import User
from django.shortcuts import redirect,HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.forms import fields
from captcha.fields import CaptchaField
from django import forms
import os,datetime 

from django.contrib.auth.decorators import login_required

#登录

def login(request):

    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        #对比输入的用户名和密码和数据库中是否一致
        print (username)
        print (password)
        user  = User.objects.filter(username__exact=username,password__exact=password)
        if user :
            response = HttpResponseRedirect('/userlist/')
            response.set_cookie('cookie_username',username,3600)
            return response
        else:
            return render_to_response('login.html')
    else:
        return render_to_response('login.html',context_instance=RequestContext(request))

#列表所有用户

def user_list(request):

    u_list = User.objects.all()

    return render_to_response('userlist.html',{'u_list':u_list})

#添加用户
def add_user(request):
    if request.method == "GET":
        return render_to_response('adduser.html')
    elif request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        User.objects.create(username=username,password=password,email=email,phone=phone)

        return HttpResponseRedirect('/userlist/')

#编辑用户
def edit_user(request,nid):
    if request.method == "GET":
        obj = User.objects.get(id=nid)
        return render_to_response('edituser.html',{'obj': obj})
    elif request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        User.objects.filter(id=nid).update(username=username,password=password,email=email,phone=phone)

        return HttpResponseRedirect('/userlist/')

#删除用户  
def del_user(request,nid):
    User.objects.filter(id=nid).delete()

    return HttpResponseRedirect("/userlist/")

login.html页面

<html>
<head>
    <title>登录</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
#form_id{width:360px;height:400px;margin:200px auto;padding-top:80px;text-align:center;background-color:#fff;}
    </style>
</head>
<body style="background-repeat: no-repeat;background-color: ">
<div id="form_id">
<form class="form-horizontal" action="/login/" method="post"> 
   {% csrf_token %}
                <div class="control-group" >   
                      <label class="control-label" for="inputUsername">用户名</label>   
                        <div class="controls">  
                         <input type="text" value="{{ form.email.value|default:'' }}" name="username" placeholder="输入常用邮箱">  
                        <span style="color:red;"> {{form.username.errors}}</span>
                        </div>  
                        </div>  
                        <div class="control-group">  
                        <label class="control-label" for="inputPassword">密码</label>   
                        <div class="controls">    
                          <input type="password"  value="{{ form.password.value|default:'' }}" name="password" placeholder="登录密码">    
                           <span style="color:red;"> {{form.password.errors}}</span>
           <div class="control-group">  
             <div class="controls">     
                 <button type="submit" class="btn  btn-primary">登录</button>
              </div> 
            </div>
      </form> 
</div>
</body>

</html>

userlist用户列表页面

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<h1 style="text-align: center">Welcome!</h1>
    <h3 style="text-align: center">用户列表-首页</h3>
    <ul>
        {% for row in u_list %}
            <li>{{ row.username }}   {{ row.password }} {{ row.email }} {{ row.phone }}&nbsp;&nbsp;&nbsp;<a href="/edituser/{{row.id}}/">编辑</a> <a href="/adduser/">添加</a> <a href="/deluser/{{row.id}}">删除</a></li>
        {% endfor %}
    </ul>
</body>
</html>

添加用户页面adduser.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>添加用户</h1>
<!--     {% csrf_token %} -->
    <form action="/adduser/" method="POST">
        {% csrf_token %}
         <div>
        <div><label>用户名:</label></div>
        <input type="text" name="username" >
        </div>
         <div>
          <div><label>密码:</label></div>
          <input type="password" name="password" >
         </div> 
          <div>
          <div><label>郵箱:</label></div>
          <input type="text" name="email" >
         </div> 
          <div>
          <div><label>電話:</label></div>
          <input type="text" name="phone" >
         </div> 
        <input type="submit" value="提交" />
    </form>
</body>

</html>

编辑用户edituser.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>编辑用户</h1>
      
    <form method="POST" action="/edituser/{{obj.id}}/">
        {% csrf_token %}
        <div>
         
        <div><label>用户名:</label></div>
        <input type="text" name="username" value="{{obj.username}}" >
        </div>
        
         <div>
          <div><label>密码:</label></div>
          <input type="password" name="password"  value="{{obj.password}}" >
         </div> 
         <div>
          <div><label>郵箱:</label></div>
          <input type="text" name="email"  value="{{obj.email}}"  >
         </div>
         <div>
          <div><label>電話:</label></div>
          <input type="text" name="phone" value="{{obj.phone}}">
         </div>
        <input type='submit' value="提交" />
    </form>
</body>

</html>

最后在urls.py


# -*- coding: utf-8 -*- 
from django.conf.urls import patterns, include, url
from django.contrib import admin


urlpatterns = patterns("",
    url(r'^admin/', include(admin.site.urls)),
    url(r'^upload/$', 'login.views.upload',name='upload'),
    url(r'^login/$', 'login.views.login',name='login'),
    url(r'^userlist/$', 'login.views.user_list',name='userlist'),
    url(r'^adduser/$', 'login.views.add_user',name='adduser'),
    url(r'^edituser/(\d+)/$', 'login.views.edit_user',name='edituser'),
    url(r'^deluser/(\d+)/$', 'login.views.del_user',name='deluser'),
    

)





简单的练习,希望对初学者有帮助。

阅读更多
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭