Catalog
1、 Create a template page
2、 Create a home page
3、 Add an error prompt page
4、 Add album information
4.1、 Write the web part
4.2、 Writing back-end parts
5、 View album information
5.1、 Write the web part
5.2、 Write back-end code
6、 Modify album information
6.1、 Write the web part
6.2、 Writing back-end parts
7、 Delete album information
7.1、 Writing back-end parts
8、 additional : Click on the picture to enlarge
8.1、 Writing back-end parts
The last article is mainly about the preparation of the album management system , Friends who don't know can go to my homepage to check .
Django-- Online album management system (1)_ Orange hahaha ~ The blog of -CSDN Blog
We first in templates Right click in the folder to create a new one base The web file
, Used as a template page , Write code :
<!-- Template page -->
<h1> Online album information management system </h1>
<a href="{% url 'index' %}"> Put it back on the front page </a> | <a href="{% url 'look' 1 %}"> Browse album information </a> | <a href="{% url 'add' %}"> Publish album information </a>
<hr/>
a In the label is url: Reverse DNS .
index To jump to a page , The following numbers are parameters .
This benefit will be more flexible , When one url When the configured address changes , The location of the generated address on the page using reverse parsing does not need to change .
url Reverse resolution of
stay urls.py Add path to :
path('',views.index,name="index"),
path('look/<int:pIndex>',views.look,name="look"),
path('add',views.add,name="add"),
stay views.py Add features to :
def index(request):
return render(request, "index.html") # home page
def add(request):
return render(request, "addAlbum.html") # Add a page
Still templates Create a index The web file , Write code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> home page </title>
</head>
<body>
<center>
{% include "base.html" %} <!-- Load the template and render with the parameters in the tag -->
<h1> home page </h1>
</center>
</body>
</html>
So that when the operation is wrong , There is a reminder function .
stay templates Create a ifo The web file , Write code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
{% include 'base.html' %}
<!-- Prompt error -->
{% if info != null %}
<h3> {
{ info }} </h3>
{% if status == 200 %}
<a href="{% url 'look' 1 %}"> Return to the browse page </a>
{% elif status == 400 %}
<a href="javascript:history.go(-1)"> Back to previous page </a>
{% endif %}
<br/>
<br/>
{% endif %}
<!-- Upload and modify the picture display -->
{% if image != null %}
<img src='/static/{
{image}}' width="500" height="330"/>
{% endif %}
<!-- Browse the pictures -->
{% if imageLook != null %}
<br/>
<a href="javascript:history.go(-1)"> Back to previous page </a>
<br/>
<br/>
<img src='/static/{
{ imageLook }}'/>
{% endif %}
</center>
</body>
</html>
Here are some django Use of labels , If you don't, I suggest you go to cram for some basic knowledge , I think everyone knows how to use these labels , Otherwise, it would be troublesome .
The content is all on it , Include the code associated with the following , What you can't understand now , There may be new experience when you look back at the back .
Additions and deletions , Let's start with growth .
stay templates Create a addAlbum The web file , Write code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Publish album information </title>
<script>
// When you select a picture , The selected image will be immediately displayed below
function setImagePreview(avalue) {
var docObj = document.getElementById("doc");
var imgObjPreview = document.getElementById("preview");
if (docObj.files && docObj.files[0]) {
imgObjPreview.style.width = '500px';
imgObjPreview.style.height = '330px';
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
return true;
}
</script>
</head>
<body>
<center>
{% include 'base.html' %}
<h2> Add album information </h2>
<form method="post" action="{% url 'addImage' %}" enctype="multipart/form-data">
{% csrf_token %} <!-- Methods to prevent cross site attacks -->
<table width="400">
<tr>
<td> title :</td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td> picture :</td>
<td><input type="file" name="pic" id="doc" onchange="setImagePreview(this)"/><br></td>
</tr>
</table>
<input type="submit" value=" add to "> <input type="reset" value=" Reset ">
</form>
<br/>
<img width="500" height="330" id="preview"/>
</center>
</body>
</html>
Be careful :
request.FILES
stay urls.py Add a path to the file :
path('addImage',views.addImage,name="addImage"),
stay views.py Add functions to the file :
from PIL import Image
from ablumapp.models import Album
def addImage(request):
try:
# There is not much to say about the analysis of web transmission content , If you don't understand, you can go to Baidu for related content
fileTitle = request.POST['title']
fileImage = request.FILES.get("pic", None)
fileTtpe = fileImage.name.split('.').pop() # Get the suffix of the picture , Know what type
if fileImage == None:
content = {"info": " There is no upload file !","status":400}
return render(request, "info.html", content)
if fileTitle == '':
content = {"info": " Please enter a title !","status":400}
return render(request, "info.html", content)
if fileTtpe.lower() != "jpg" and fileTtpe.lower() != "png" and fileTtpe.lower() != "jpeg":
content = {"info": " Please select a picture file !","status":400}
return render(request, "info.html", content)
# Determine whether the title is repeated in the database
mod = Album.objects # ablumapp.models Under the Album class
ulist = mod.filter(title=fileTitle)
if len(ulist) == 0:
filename = request.POST['title'] + "." + fileTtpe # Combined file name
# Previously created static The folder has served its purpose , It is used to store uploaded pictures
Imagefile = open("./static/" + filename, "wb+")
for chuck in fileImage.chunks():
Imagefile.write(chuck)
Imagefile.close()
# Perform picture scaling
im = Image.open("./static/" + filename)
im.thumbnail((75, 75))
im.save("./static/small/s_" + filename, None) # Remember in static Create a small Folder , Used to store zoomed pictures .
# Add records
ob = Album()
ob.title = fileTitle
ob.type = fileTtpe
ob.save()
content = {"info": " Upload successful !", "image": filename,"status":200}
else:
content = {"info": " Duplicate title , Please re-enter ","status":400}
except:
content = {"info": " Upload failed !","status":400}
return render(request, "info.html", content)
render The role of methods :
Combine a given template with a given context Dictionary , And return a rendered HttpResponse object .
Generally speaking, it means to put context The content of , Load in templates File defined in , And render through the browser .
stay templates Create a addAlbum The web file , Write code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Browse album information </title>
<script>
// User defined execution information deletion prompt judgment , Parameters uu Was successfully deleted url Address
function doDel(url){
if(confirm(" Are you sure you want to delete ?")){
// Page Jump
window.location=url;
}
}
</script>
</head>
<body>
<center>
{% include 'base.html' %}
<h3> Browse album picture information </h3>
<form method="get" action="{% url 'look' 1 %}">
title :<input type="text" name="keyword"/>
<input type="submit" value=" Search for "/>
</form>
<br/>
<table width="800" border="1">
<tr>
<th>ID Number </th>
<th> title </th>
<th> picture </th>
<th> Time </th>
<th> operation </th>
</tr>
{% for album in AlbumList %}
<tr>
<td>{
{ album.id }}</td>
<td>{
{ album.title }}</td>
<td >
<a href="{% url 'lookBigImage' album.id %}"><img src='/static/small/s_{
{ album.title }}.{
{ album.type }}'/></a>
<!-- Click to zoom in to view the picture -->
</td>
<td>{
{ album.add_time|date:'Y-m-d' }}</td>
<td>
<a href="{% url 'updata' album.id %}"> edit </a>
<a href="javascript:doDel('{% url 'del' album.id %}');"> Delete </a>
</td>
</tr>
{% endfor %}
</table>
<br/>
<!-- Paging function -->
<!-- Like this {% url 'look' pIndex|add:-1 %}, Followed by django Filter , You can find out by yourself , Don't go into details -->
<a href="{% url 'look' pIndex|add:-1 %}{
{mywhere}}"> The previous page </a>
{% for p in pageList %}
{% if pIndex == p %}
<a href="{% url 'look' p %}{
{mywhere}}" >{
{ p }}</a>
{% else %}
<a href="{% url 'look' p %}{
{mywhere}}" >{
{ p }}</a>
{% endif %}
{% endfor %}
<a href="{% url 'look' pIndex|add:1 %}{
{mywhere}}"> The next page </a>
<br/>
<br/>
<br/>
</center>
</body>
</html>
The corresponding paging content cannot be understood , You can see the following back-end code , Look at it in combination .
stay urls.py Add :
path('look/<int:pIndex>',views.look,name="look"),
stay views.py Add :
def look(request, pIndex=1):
try:
kw = request.GET.get('keyword', None)
mywhere = ""
if kw != None:
ulist = Album.objects.filter(title__contains=kw)
mywhere = "?keyword=" + kw
else:
ulist = Album.objects.all()
p = Paginator(ulist, 5) # Returns the paging object , The parameter is list data , Number of pieces of data per side
# Set page number boundary
if pIndex < 1:
pIndex = 1
if pIndex >= p.num_pages: # Total number of pages
pIndex = p.num_pages
# Subscript with 1 Start , If the page number provided does not exist , Throw out InvalidPage abnormal . This method is more convenient and fast paging , Enter the page number , The data corresponding to the number of pages will be put back , The screening done here .
list = p.page(pIndex)
content = {"AlbumList": list, "pIndex": pIndex, "pageList": p.page_range, "mywhere": mywhere}
return render(request, "lookAlbum.html", content)
except:
content = {"info": " No user information found ","status":400}
return render(request, "info.html", content)
Tell me about pagination ideas :
When you click search , The input content will be (kw) Send to back end , Set up mywhere = "?keyword=" + kw
, Perform fuzzy search on all database titles , Put it in a list , Take out the data of the corresponding page and put it back in the page . In short , Know the web address ? The back is get Access parameters of type ,(http://127.0.0.1:8000/look/1?keyword=3), Like this , See the code .
stay templates Create a updata The web file , Write code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Modify album information </title>
<script>
// Same as adding , Reduce the size to show immediately
function setImagePreview(avalue) {
var docObj = document.getElementById("doc");
var imgObjPreview = document.getElementById("preview");
if (docObj.files && docObj.files[0]) {
// Under Firefox , Set directly img attribute
imgObjPreview.style.width = '500px';
imgObjPreview.style.height = '330px';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
// firefox 7 The above version cannot use the above getAsDataURL() How to get , We need a way
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
return true;
}
</script>
</head>
<body>
<center>
{% include 'base.html' %}
<h2> Modify album information </h2>
<form method="post" action="{% url 'doupdata' id %}" enctype="multipart/form-data">
{% csrf_token %}
<table width="400">
<tr>
<td> title :</td>
<td><input type="text" name="title" value="{
{ title }}"></td>
</tr>
<tr>
<td> picture :</td>
<td><input type="file" name="pic" id="doc" onchange="setImagePreview(this)"/><br></td>
</tr>
</table>
<input type="submit" value=" edit "> <input type="reset" value=" Reset ">
</form>
<br/>
<br/>
<img src='/static/{
{ title }}.{
{ type }}' width="500" height="330" id="preview"/>
</center>
</body>
</html>
stay urls.py Add :
path('updata/<int:uid>',views.updata,name="updata"), # Click the modified routing path on the browse page
path('doupdata/<int:uid>',views.doupdata,name="doupdata"), # The function of executing the modification command
stay views.py Add :
# Record the information and jump to the modification page
def updata(request, uid):
# Inquire about
mod = Album.objects
objects = mod.filter(id=uid)[0]
content = {"id": objects.id, "title": objects.title, "type": objects.type, "time": objects.add_time}
return render(request, "updata.html", content)
# Modify the function
def doupdata(request, uid):
try:
# Determine whether the title is repeated
mod = Album.objects
ulist = mod.filter(title=request.POST['title']).exclude(id=uid)
if len(ulist) == 0:
fileImage = request.FILES.get("pic", None)
if fileImage == None:
content = {"info": " There is no upload file !","status":400}
return render(request, "info.html", content)
fileType = fileImage.name.split('.').pop()
if fileType.lower() != "jpg" and fileType.lower() != "png" and fileType.lower() != "jpeg":
content = {"info": " Please select a picture file !","status":400}
return render(request, "info.html", content)
ob = Album.objects.get(id=uid)
oldTitle = ob.title + "." + ob.type
# Delete old photos
os.remove("./static/small/s_" + oldTitle)
os.remove("./static/" + oldTitle)
# Modify the title
ob.title = request.POST['title']
# Modification type
ob.type = fileType
filename = request.POST['title'] + "." + fileType
# Save pictures to local
Imagefile = open("./static/" + filename, "wb+")
for chuck in fileImage.chunks():
Imagefile.write(chuck)
Imagefile.close()
# Perform image zoom and save to local
im = Image.open("./static/" + filename)
im.thumbnail((75, 75))
im.save("./static/small/s_" + filename, None)
ob.save()
content = {"info": " Modification successful !","status":200}
else:
content = {"info": " Duplicate title , Please re-enter ","status":400}
except:
content = {"info": " Modification failed !","status":400}
return render(request, "info.html", content)
It should be known here , There are notes in the corresponding sections .
The web page section is the same as the 5 Step combination , Added deletion prompt , In case of delay :
stay urls.py Add :
path('delete/<int:uid>',views.delete,name="del"),
stay views.py Add :
def delete(request, uid):
try:
ob = Album.objects.get(id=uid)
oldTitle = ob.title + "." + ob.type
# Delete old photos
os.remove("./static/small/s_" + oldTitle)
os.remove("./static/" + oldTitle)
# Delete database information
ob.delete()
content = {"info": " Delete successful !","status":200}
except:
content = {"info": " Delete failed !","status":400}
return render(request, "info.html", content)
Please refer to page 5 spot , Picture label is a The label contains .
stay urls.py Add :
path('lookBigImage/<int:uid>',views.lookBigImage,name="lookBigImage"),
stay views.py Add :
def lookBigImage(request, uid):
try:
ob = Album.objects.get(id=uid)
image = ob.title + "." + ob.type
content = {"imageLook": image}
return render(request, "info.html", content)
except:
content = {"info": " Check the failure ","status":400}
return render(request, "info.html", content)
Okay , This online album management system is finished , Run to see the effect , If there is something you can't understand, just leave a message in the comment area or send a private message to me !
Without permission , Do not reprint !
pycharm: connection to Python
List of articles One 、 Prefac