二、Django用Eclipse编写一个登录界面

时间:2024-07-31 14:03:50

一、Django用Eclipse编写一个登录界面

二、Django用Eclipse编写一个登录界面Ajax和Django交互

  各软件版本:Python 2.7.14,django 1.6.11

    

原来已经写好一个登录界面了,不过那个是系统自动的。现在我们自己动手写一个

1.我们在项目admin下新建一个

二、Django用Eclipse编写一个登录界面

二、Django用Eclipse编写一个登录界面

2.新建项目online:

二、Django用Eclipse编写一个登录界面

3.把urls.py拷贝一份到online项目目录下:

然后开始修改admin项目下的settings.py:

"""
Django settings for admin project. For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
""" # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.conf.global_settings import STATIC_ROOT
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't2ruk$q%dl$t^$15=4tj!js*_2yal3+f&@hg_9__ww=p#5x9j&' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'online'
) MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
) ROOT_URLCONF = 'admin.urls' WSGI_APPLICATION = 'admin.wsgi.application' # Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} # Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True APPEND_SLASH = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
#template
TEMPLATE_DIRS=(
'D:\\own_own\\admin\src\\online\\templates'
)

4.然后开始修改admin项目下的urls.py:

 from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite5.views.home', name='home'), url(r'^admin/', include(admin.site.urls)),
url(r'^online/', include('online.urls')),
)

5.如果需要新建数据库表的话,可以修改online项目下的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

然后执行命令行:win+r可进入cmd中到项目online目录下找到manage.py。执行如下命令:

 先 cd 进入 manage.py 所在的那个文件夹下,输入下面的命令

 # Django 1.6.x 及以下
python manage.py syncdb # Django 1.7 及以上的版本需要用以下命令
python manage.py makemigrations
python manage.py migrate

Django 1.6.x 以下版本 显示大概如下:

二、Django用Eclipse编写一个登录界面

Django 1.7.x 以上版本的同学会看到

二、Django用Eclipse编写一个登录界面

6.在online项目下的urls.py中引用定义登录用的方法 

 from django.conf.urls import patterns, url
from online import views urlpatterns = patterns('',
url(r'^$', views.login, name='login'),
url(r'^login/$',views.login,name = 'login'),
url(r'^regist/$',views.regist,name = 'regist'),
url(r'^index/$',views.index,name = 'index'),
url(r'^logout/$',views.logout,name = 'logout'), )

7.在views.py中定义上面引用的方法。然后保存urls.py就不报错了。

 # -*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django import forms
from models import User
import json
#表单
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.create(username= username,password=password)
return HttpResponse('regist success!!')
else:
uf = UserForm()
return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req)) #登录
def login(req):
if req.method == 'POST':
data = req.POST
jstr = json.dumps(data) # 把传入的参数json话
decodejson = json.loads(jstr) # 封装json 然后获取其中的某个字段
username = decodejson['username']
print('username==%s'%username)
req.session['username'] = username #吧username存储到session中
responseData = {'state':0,'msg':'success','username':username}
return HttpResponse(json.dumps(responseData,ensure_ascii=False,encoding="utf-8"), content_type="application/json")
else:
responseData = {'state':1,'msg':'faile'}
return render(req, 'login.html', json.dumps(responseData))
#登陆成功
def index(req):
username = req.session.get('username',False) # 获取session中的username
print(username)
return render_to_response('index.html' ,{'username':username}) #退出
def logout(req):
response = HttpResponse('logout !!')
#清理cookie里保存username
response.delete_cookie('username')
return response

8.方法写好后开始新建登录所需的模板和js以及css

online项目下的templates中新建 index.html,login.html,regist.html

index.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head> <body>
<h1>欢迎 {{username}} !</h1>
<br>
<a href="http://127.0.0.1:8000/online/logout/">退出</a>
</body>
</html>

login.html

<!DOCTYPE html>

<html>

    <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>登录</title>
<link rel="stylesheet" href="/static/plugins/layui/css/layui.css" media="all" />
<link rel="stylesheet" href="/static/css/login.css" />
</head> <body class="beg-login-bg">
<div class="beg-login-box">
<header>
<h1>后台登录</h1>
</header>
<div class="beg-login-main">
<form enctype="multipart/form-data" class="layui-form" method="post"><input name="__RequestVerificationToken" type="hidden" value="fkfh8D89BFqTdrE2iiSdG_L781RSRtdWOH411poVUWhxzA5MzI8es07g6KPYQh9Log-xf84pIR2RIAEkOokZL3Ee3UKmX0Jc8bW8jOdhqo81" />
<div class="layui-form-item">
<label class="beg-login-icon">
<i class="layui-icon"></i>
</label>
<input id="id_username" type="text" name="username" lay-verify="username" autocomplete="off" placeholder="这里输入登录名" class="layui-input">
</div>
<div class="layui-form-item">
<label class="beg-login-icon">
<i class="layui-icon"></i>
</label>
<input id="id_password" type="password" name="password" lay-verify="password" autocomplete="off" placeholder="这里输入密码" class="layui-input">
</div>
<div class="layui-form-item">
<div class="beg-pull-left beg-login-remember">
<label>记住帐号?</label>
<input type="checkbox" name="rememberMe" value="true" lay-skin="switch" checked title="记住帐号">
</div>
<div class="beg-pull-right">
<button class="layui-btn layui-btn-primary" lay-submit lay-filter="syslogin" id='syslogin'>
<i class="layui-icon"></i> 登录
</button>
</div>
<div class="beg-clear"></div>
</div>
</form>
</div>
<footer>
<p>Beginner © www.zhengjinfan.cn</p>
</footer>
</div>
<script type="text/javascript" src="/static/plugins/layui/layui.js"></script>
<script>
layui.use(['layer', 'form'], function() {
var layer = layui.layer,
$ = layui.jquery,
form = layui.form(); $('#syslogin').on('click',function(){
var username = $('#id_username').val();
var password = $('#id_password').val();
var cate = {'username':username,'password':password} ;
$.ajax({
url:'/online/login/', //url相当于 form 中的 action
type:'POST', //type相当于form 中的 method
data:cate, // data:传人的数据 dat为任意设置的内容,相当于模版中的{author:lee}
dataType: "text",
success:function(result){ //成功执行 console.log() 函数 arg 为HttpResponse 返回的值
var data = JSON.parse(result)
console.info(result) //打印obj
if(data.state==0){
document.cookie="username="+data.username;
window.location.href="/online/index/";
}else{
alert("失败并不")
}
},
error:function(){ //失败
console.info('失败')
}
});
})
});
</script>
</body> </html>

regist.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>注册</title>
</head> <body>
<h1>注册页面:</h1>
<form method = 'post' enctype="multipart/form-data">
{% csrf_token %}
{{uf.as_p}}
<input type="submit" value = "ok" />
</form>
<br>
<a href="http://127.0.0.1:8000/online/login/">登陆</a>
</body>
</html>

 9.在online项目中新建static文件夹

二、Django用Eclipse编写一个登录界面

login.css

.beg-login-bg {
/* background: url(../Images/login-bg-1.jpg) no-repeat center center fixed; */
background-color: #393D49;
} .beg-login-box {
width: 450px;
height: 330px;
margin: 10% auto;
background-color: rgba(255, 255, 255, 0.407843);
border-radius: 10px;
color: aliceblue;
} .beg-login-box header {
height: 39px;
padding: 10px;
border-bottom: 1px solid aliceblue;
} .beg-login-box header h1 {
text-align: center;
font-size: 25px;
line-height: 40px;
} .beg-login-box .beg-login-main {
height: 185px;
padding: 30px 90px 0;
} .beg-login-main .layui-form-item {
position: relative;
} .beg-login-main .layui-form-item .beg-login-icon {
position: absolute;
color: #cccccc;
top: 10px;
left: 10px;
} .beg-login-main .layui-form-item input {
padding-left: 34px;
} .beg-login-box footer {
height: 35px;
padding: 10px 10px 0 10px;
} .beg-login-box footer p {
line-height: 35px;
text-align: center;
} .beg-pull-left {
float: left !important;
} .beg-pull-right {
float: right !important;
} .beg-clear {
clear: both;
} .beg-login-remember {
line-height: 38px;
} .beg-login-remember .layui-form-switch {
margin-top: 0px;
} .beg-login-code-box {
position: relative;
padding: 10px;
} .beg-login-code-box input {
position: absolute;
width: 100px;
} .beg-login-code-box img {
cursor: pointer;
position: absolute;
left: 115px;
height: 38px;
}

layout.css

.beg-layout-container{
/*min-width: 1024px;*/
}
.beg-layout-container .beg-layout-main{
position: absolute;
}
.beg-layout-container .beg-layout-header{
background-color: #FFFFFF;
height: 55px;
position: fixed;
width: 100%;
min-width: 800px;
border-bottom: 5px solid #1AA094;
}
.beg-layout-container .beg-layout-header .beg-layout-logo{
width: 200px;
height: 60px;
text-align: center;
line-height: 60px;
}
.beg-layout-container .beg-layout-header .beg-layout-side-toggle{
position: absolute;
cursor: pointer;
z-index:;
left: 200px;
color: white;
text-align: center;
width: 30px;
height: 30px;
background-color: #1AA094;
line-height: 30px;
top: 25%;
}
.beg-layout-container .beg-layout-header .beg-layout-side-toggle:hover{
background-color: #5FB878;
}
.beg-layout-container .beg-layout-header .beg-layout-menu{
top:;
left:230px;
}
.beg-layout-header .beg-layout-menu .beg-layout-nav{
background: none;
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-nav-item{
line-height: 60px;
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-nav-item .layui-nav-more{
top:27px
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-nav-item .layui-nav-mored{
top:20px
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-this{
color: #FFFFFF;
background-color: #4E5465;
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-this:after,.beg-layout-header .layui-nav-bar{
background-color: #4E5465;
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-nav-item a{
color: #393D49;
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-this a{
color: #FFFFFF;
}
.beg-layout-header .beg-layout-menu .beg-layout-nav .layui-nav-item a:hover{
color: #FFFFFF;
background-color: #4E5465;
}
.beg-layout-header .beg-layout-panel{
right: 10px;
}
.beg-layout-header .beg-layout-panel .beg-layout-nav{
background: none;
}
.beg-layout-header .beg-layout-panel .beg-layout-nav a{
color: #393D49;
}
.beg-layout-header .beg-layou-head{ }
.beg-layout-header .beg-layou-head img{
width: 40px; height: 40px; border-radius: 100%;
} .beg-layout-container .beg-layout-side{
background-color: #393D49;
color: #FFFFFF;
top: 60px;
}
.beg-layout-container .beg-layout-body{
top: 60px;
height: auto;
}
.beg-layout-container .beg-layout-body .layout-nav-card cite{
font-style: normal;
padding-left: 5px;
}
.beg-layout-body iframe{
width: 100%;
border:;
height: 99.5%;
}
.beg-layout-container .beg-layout-footer{
line-height: 44px;
text-align: center;
} .layout-tab-contextmenu {width: 135px; background-color: #CCCCCC;position: absolute; z-index:;display: none;}
.layout-tab-contextmenu .layui-nav{
padding: 5px 3px;
}
.layout-tab-contextmenu .layui-nav .layui-nav-item{
line-height: 27px;width: 100%;
}
.layout-tab-contextmenu .layui-nav .layui-nav-item:hover{
background-color: #5FB878;
}
.layout-tab-contextmenu .layui-nav .layui-nav-item a{
text-align: left;
} .layout-tab-contextmenu .layui-nav .layui-this:after, .layout-tab-contextmenu .layui-nav-bar {
transition: none; -webkit-transition:none; background: none;
}
.admin-contextmenu{
position: absolute;line-height: 36px;padding: 5px 0;
border: 1px solid #d2d2d2;background-color: white;z-index:;border-radius: 2px;white-space: nowrap;top:30px;
/*width: 100px;height: 200px; */
}
.admin-contextmenu ul li{
padding: 0 15px;
}
.admin-contextmenu ul li:hover{
background-color: #eee;
cursor: pointer;
} @media screen and (max-width: 1024px) {
.beg-layout-menu cite{
display: none;
} }

layui.js

/** layui-v1.0.9_rls MIT License By http://www.layui.com */
;!function(e){"use strict";var t=function(){this.v="1.0.9_rls"};t.fn=t.prototype;var n=document,o=t.fn.cache={},i=function(){var e=n.scripts,t=e[e.length-1].src;return t.substring(0,t.lastIndexOf("/")+1)}(),r=function(t){e.console&&console.error&&console.error("Layui hint: "+t)},l="undefined"!=typeof opera&&"[object Opera]"===opera.toString(),a={layer:"modules/layer",laydate:"modules/laydate",laypage:"modules/laypage",laytpl:"modules/laytpl",layim:"modules/layim",layedit:"modules/layedit",form:"modules/form",upload:"modules/upload",tree:"modules/tree",table:"modules/table",element:"modules/element",util:"modules/util",flow:"modules/flow",carousel:"modules/carousel",code:"modules/code",jquery:"modules/jquery",mobile:"modules/mobile","layui.all":"dest/layui.all"};o.modules={},o.status={},o.timeout=10,o.event={},t.fn.define=function(e,t){var n=this,i="function"==typeof e,r=function(){return"function"==typeof t&&t(function(e,t){layui[e]=t,o.status[e]=!0}),this};return i&&(t=e,e=[]),layui["layui.all"]||!layui["layui.all"]&&layui["layui.mobile"]?r.call(n):(n.use(e,r),n)},t.fn.use=function(e,t,u){function s(e,t){var n="PLaySTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/;("load"===e.type||n.test((e.currentTarget||e.srcElement).readyState))&&(o.modules[m]=t,y.removeChild(p),function i(){return++v>1e3*o.timeout/4?r(m+" is not a valid module"):void(o.status[m]?c():setTimeout(i,4))}())}function c(){u.push(layui[m]),e.length>1?f.use(e.slice(1),t,u):"function"==typeof t&&t.apply(layui,u)}var f=this,d=o.dir=o.dir?o.dir:i,y=n.getElementsByTagName("head")[0];e="string"==typeof e?[e]:e,window.jQuery&&jQuery.fn.on&&(f.each(e,function(t,n){"jquery"===n&&e.splice(t,1)}),layui.jquery=jQuery);var m=e[0],v=0;if(u=u||[],o.host=o.host||(d.match(/\/\/([\s\S]+?)\//)||["//"+location.host+"/"])[0],0===e.length||layui["layui.all"]&&a[m]||!layui["layui.all"]&&layui["layui.mobile"]&&a[m])return c(),f;var p=n.createElement("script"),h=(a[m]?d+"lay/":o.base||"")+(f.modules[m]||m)+".js";return p.async=!0,p.charset="utf-8",p.src=h+function(){var e=o.version===!0?o.v||(new Date).getTime():o.version||"";return e?"?v="+e:""}(),o.modules[m]?!function g(){return++v>1e3*o.timeout/4?r(m+" is not a valid module"):void("string"==typeof o.modules[m]&&o.status[m]?c():setTimeout(g,4))}():(y.appendChild(p),!p.attachEvent||p.attachEvent.toString&&p.attachEvent.toString().indexOf("[native code")<0||l?p.addEventListener("load",function(e){s(e,h)},!1):p.attachEvent("onreadystatechange",function(e){s(e,h)})),o.modules[m]=h,f},t.fn.getStyle=function(t,n){var o=t.currentStyle?t.currentStyle:e.getComputedStyle(t,null);return o[o.getPropertyValue?"getPropertyValue":"getAttribute"](n)},t.fn.link=function(e,t,i){var l=this,a=n.createElement("link"),u=n.getElementsByTagName("head")[0];"string"==typeof t&&(i=t);var s=(i||e).replace(/\.|\//g,""),c=a.id="layuicss-"+s,f=0;a.rel="stylesheet",a.href=e+(o.debug?"?v="+(new Date).getTime():""),a.media="all",n.getElementById(c)||u.appendChild(a),"function"==typeof t&&!function d(){return++f>1e3*o.timeout/100?r(e+" timeout"):void(1989===parseInt(l.getStyle(n.getElementById(c),"width"))?function(){t()}():setTimeout(d,100))}()},t.fn.addcss=function(e,t,n){layui.link(o.dir+"css/"+e,t,n)},t.fn.img=function(e,t,n){var o=new Image;return o.src=e,o.complete?t(o):(o.onload=function(){o.onload=null,t(o)},void(o.onerror=function(e){o.onerror=null,n(e)}))},t.fn.config=function(e){e=e||{};for(var t in e)o[t]=e[t];return this},t.fn.modules=function(){var e={};for(var t in a)e[t]=a[t];return e}(),t.fn.extend=function(e){var t=this;e=e||{};for(var n in e)t[n]||t.modules[n]?r("模块名 "+n+" 已被占用"):t.modules[n]=e[n];return t},t.fn.router=function(e){for(var t,n=(e||location.hash).replace(/^#/,"").split("/")||[],o={dir:[]},i=0;i<n.length;i++)t=n[i].split("="),/^\w+=/.test(n[i])?function(){"dir"!==t[0]&&(o[t[0]]=t[1])}():o.dir.push(n[i]),t=null;return o},t.fn.data=function(t,n){if(t=t||"layui",e.JSON&&e.JSON.parse){if(null===n)return delete localStorage[t];n="object"==typeof n?n:{key:n};try{var o=JSON.parse(localStorage[t])}catch(i){var o={}}return n.value&&(o[n.key]=n.value),n.remove&&delete o[n.key],localStorage[t]=JSON.stringify(o),n.key?o[n.key]:o}},t.fn.device=function(t){var n=navigator.userAgent.toLowerCase(),o=function(e){var t=new RegExp(e+"/([^\\s\\_\\-]+)");return e=(n.match(t)||[])[1],e||!1},i={os:function(){return/windows/.test(n)?"windows":/linux/.test(n)?"linux":/iphone|ipod|ipad|ios/.test(n)?"ios":void 0}(),ie:function(){return!!(e.ActiveXObject||"ActiveXObject"in e)&&((n.match(/msie\s(\d+)/)||[])[1]||"11")}(),weixin:o("micromessenger")};return t&&!i[t]&&(i[t]=o(t)),i.android=/android/.test(n),i.ios="ios"===i.os,i},t.fn.hint=function(){return{error:r}},t.fn.each=function(e,t){var n,o=this;if("function"!=typeof t)return o;if(e=e||[],e.constructor===Object){for(n in e)if(t.call(e[n],n,e[n]))break}else for(n=0;n<e.length&&!t.call(e[n],n,e[n]);n++);return o},t.fn.stope=function(t){t=t||e.event,t.stopPropagation?t.stopPropagation():t.cancelBubble=!0},t.fn.onevent=function(e,t,n){return"string"!=typeof e||"function"!=typeof n?this:(o.event[e+"."+t]=[n],this)},t.fn.event=function(e,t,n){var i=this,r=null,l=t.match(/\(.*\)$/)||[],a=(t=e+"."+t).replace(l,""),u=function(e,t){var o=t&&t.call(i,n);o===!1&&null===r&&(r=!1)};return layui.each(o.event[a],u),l[0]&&layui.each(o.event[t],u),r},e.layui=new t}(window);

layui.js

10.在admin项目中修改settings.py

新增:

APPEND_SLASH = False #编码转换的时候用到了

新增:

STATIC_ROOT = os.path.join(BASE_DIR,'static') #定义js中用到的static路径
#template
TEMPLATE_DIRS=(
'D:\\own_own\\admin\src\\online\\templates' #指定静态页面所在的目录
)

11.然后启动运行 Run As ->PyDev: Django

访问路径:http://127.0.0.1:8000/online/login/

访问路径不用弄错了,注意前后都有 /

然后就是登录界面:

二、Django用Eclipse编写一个登录界面

随便输入登陆账户和密码,然后就能跳转到index.html页面

二、Django用Eclipse编写一个登录界面

后面会陆续有新的文章,我会继续学习分享

相关文件主要来自网络和个人编程。支持转载