Django官方文档:https://docs.djangoproject.com/zh-hans/2.1/
1、创建项目:使用pyCharm新建Django项目,即可初始化Django,默认创建文件夹为:
users/xxx/pycharmProjects/untitled
*untitled为项目名称
可以看到,项目下面有:
2、查看所有命令:在相应连接cmd输入命令(pyCharm可以直接右键项目->Open in Terminal,在下方控制台输入即可):
\project> python manage.py
3、创建应用:
下面创建sign应用:
\project> python manage.py startapp sign
4、运行项目:
\project> python manage.py runserver
1、在views.py编写方法后,要在项目的urls添加相应的路由。
需要注意的点:urls需要import views才能使用、链接如admin/记得加/
views.py:
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
return render(request, "index.html")
def login_aciton(request):
if request.method =='POST':
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
response = HttpResponseRedirect('/even_manage/')
request.session['user'] = username #记录session
return response
#设置cookie
#response.set_cookie('user',username,3600)
#return HttpResponseRedirect('/even_manage/')
else:
return render(request,'index.html',{'error':'username or pasd error!'})
#这个是装饰器,用于权限控制
@login_required
def even_manage(request):
#获取浏览器cookie
#username = request.COOKIES.get('user','')
username = request.session.get('user', '')
return render(request, "even_manage.html", {"user": username})
urls.py:
from django.contrib import admin
from django.urls import path
from sign import views
urlpatterns = [
path('',views.index),
path('admin/', admin.site.urls),
path('index/',views.index),
path('accounts/login/$',views.index),
path('login_action/',views.login_aciton),
path('even_manage/',views.even_manage),
2、数据库迁移
Django默认配置sqlite3数据库,在项目文件夹下settings可查看数据库配置。
python manage.py migrate
接下来,创建数据库用户
python manage.py createsuperuser
这时,数据库创建成功,登录127.0.0.1:8000/admin/可以对数据库操作
1、直接在应用下的models.py编辑
编辑完成,记得进行数据库迁移:
python manage.py makemigration sign
from django.db import models
# Create your models here.
class Event(models.Model):
name = models.CharField(max_length=100)
limit = models.IntegerField()
status = models.BooleanField()
address = models.CharField(max_length=200)
start_time = models.DateTimeField('events time')
create_time = models.DateField(auto_now = True)
def __str__(self):
return self.name
class Guest(models.Model):
event = models.ForeignKey(Event,on_delete=models.CASCADE)
realname = models.CharField(max_length=64)
phone = models.CharField(max_length=16)
email = models.EmailField()
sign = models.BooleanField()
create_tiem = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ("event", "phone")
def __str__(self):
return self.realname
2、使admin中的表,展示多个字段:
编辑admin.py:
from django.contrib import admin
from sign.models import Event,Guest
# Register your models here.
class EventAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'status', 'address', 'start_time']
class GuestAdmin(admin.ModelAdmin):
list_display = ['realname', 'phone', 'email', 'sign', 'create_time', 'event']
admin.site.register(Event, EventAdmin)
admin.site.register(Guest, GuestAdmin)
效果图:
3、数据库的shell操作
进入shell:
模式
python manage.py shell
(1)查看数据
>>>from sign.models import Event Guest
>>> Event.objects.all()
[, ]>
>>>Guest.objects.all()
[(1)>]>
(2)增加数据
>>> from datetime import datetime
>>> el = Event(id = 2,name='红米fabuhui',limit=2000,status=True,address='beijing',start_time=datetime(2016,8,10,14,0,0))
>>> el.save()
(3)查询数据+模糊查询
>>> el = Event.objects.get(name='小米发布会')
>>> el.address
'xiaodaodonwuquyiihao'
>>> e2 = Event.objects.filter(name__contains='发布会')
>>> e2
[]>
>>>
(4)删除数据
g2 =Guest.objects.get(phone='1111111111')
g2.delete()
(5)更新数据
>>> g3 = Guest.objects.get(realname='啊吧啊吧')
>>> g3.phone= '5556'
>>> g3.save()
除了自带Django外,还可以使用MySQL数据库。
修改方法:直接修改settings.py中datebase配置,再进行一次数据库migrate即可