Python教程

python_django学习记录

本文主要是介绍python_django学习记录,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

2022春节期间学习django知识点回顾

1.创建,运行,初始化django项目:

pip安装django后,使用Django-admin startproject mysite1 创建出一个项目。

项目结构如下

 

  1. db.sqlite3文件:项目首次运行后生成的文件,是Django的默认数据库

  2. manage.py文件:命令存储,在这里插入图片描述

  3.  

     

 

运行项目,python manage.py runserver。到此一个django项目已经创建并且运行起来。

接下来初始化,在setting里面设置字符集,时区,中文等

 

 

然后就是crud函数:

from django.shortcuts import render
from .models import Book
from django.http import HttpResponse, HttpResponseRedirect


def all_book(request):
a1 = Book.objects.filter(is_active=True)
return render(request, 'all_book.html', locals())


def update_book(request, book_id):
try:
book = Book.objects.get(id=book_id, is_active=True)
except Exception as e:
print('--update book error is %s' % (e))
return HttpResponse('--the book not existed')

if request.method == 'GET':

return render(request, 'update_book.html', locals())

elif request.method == 'POST':

# 拿到数据
price = request.POST.get('qian')
# 改数据
book.price = price
# 保存数据
book.save()
return HttpResponseRedirect('/bookstore/all_book')


def delete_book(request):
# 通过获取查询字符串book_id拿到要删除的delete_id
delete_id = request.GET.get('book_id')
try:
book = Book.objects.get(id=delete_id, is_active=True)
except Exception as e:
print('cuowu %s' % e)
return HttpResponse('error')
book.is_active = False
book.save()
return HttpResponseRedirect('/bookstore/all_book')


def add_book(request):
if request.method == 'GET':
return render(request, 'add_book.html')

elif request.method == 'POST':

mz = request.POST.get('ming')
jg = request.POST.get('jiage')
a = Book(title=mz, price=jg)
a.save()
return HttpResponseRedirect('/bookstore/all_book')

 

路由

 

from django.urls import path
from . import views


urlpatterns = [
path('all_book', views.all_book),
path('update_book/<int:book_id>', views.update_book),
path('delete_book', views.delete_book),
path('add_book', views.add_book)
]

 

模型函数:

 

from django.db import models

 


class Book(models.Model):

 

def __str__(self):
return '%s_%s' % (self.title, self.price)

 

title = models.CharField('书名', max_length=50, default='', unique=True, null=True)
price = models.DecimalField('价格', max_digits=7, decimal_places=2, null=True)
is_active = models.BooleanField('是否活跃', default=True)

 

class Meta:

 

db_table = 'book'

 


class Author(models.Model):

 

name = models.CharField('姓名', max_length=11, null=False)
age = models.IntegerField('年龄', default=1)
email = models.EmailField('邮箱', null=True)

 

class Meta:

 

db_table = 'author'

 

在后台中注册自己的类函数

from django.contrib import admin
from .models import Book
# Register your models here.

# 装饰自己的类,
class BookManager(admin.ModelAdmin):

# 让后台显示哪些数据
list_display = ['id', 'title', 'price', 'is_active']

# 更换超链接
list_display_links = ['title']

# 使某个数据可编辑
list_editable = ['price']

 

# 注册类函数
admin.site.register(Book, BookManager)

 

这篇关于python_django学习记录的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!