1、百度云盘:django之创建第10-1个项目-图片上传并记录上传时间
2、主要修改的配置文件有3个,forms、views和models3个文件以及html
3、forms.py文件修改
#coding:utf-8
#这里定义html页面中用到的表单,常和views和models文件配合使用
"""
>>> help(django)
Help on package django:
PACKAGE CONTENTS
conf (package)
contrib (package)
core (package)
db (package)
dispatch (package)
forms (package)
http (package)
middleware (package)
shortcuts (package)
template (package)
templatetags (package)
test (package)
utils (package)
views (package) FUNCTIONS
get_version(*args, **kwargs) DATA
VERSION = (1, 5, 12, 'final', 0)
"""
#从django导入forms类
from django import forms class UserForm(forms.Form):
#intime = forms.DateField()#注释掉intime变量,因为html中不需要操作该项,该项为自动输入
username = forms.CharField()
headImg = forms.FileField()
4、models文件
#coding:utf-8
from django.db import models class User(models.Model):
intime = models.DateTimeField()
username = models.CharField(max_length = 30)
headImg = models.FileField(upload_to = './photos/') #图片上传之后存放在./photos/目录下,站点根目录下的photos目录中
#./代表站点根目录,../代表当前目录的上一级目录
class Meta:
db_table = 'User' def __unicode__(self):
return self.username #username 用户存放用户名,headImg 用户存放上传文件的路径
5、views文件
# Create your views here.
#coding:utf-8
from django.http import HttpResponse
import datetime
#导入templates文件所需导入库
from django.template import loader,Context
#引入Student等模块 from blog.models import *
from blog.forms import UserForm
from django.shortcuts import render,render_to_response def upload(request):
if request.method == "POST":
uf = UserForm(request.POST,request.FILES)
if uf.is_valid():
#获取表单信息
username = uf.cleaned_data['username']
headImg = uf.cleaned_data['headImg']
#intime = uf.cleaned_data['intime'] #不从表单获取数据,所以注释掉
#写入数据库
user = User()
user.username = username
user.headImg = headImg
#自动获取日期时间
now=datetime.datetime.now()
myNow=now.strftime('%Y-%m-%d %H:%M:%S')#时间,精确到秒
#myNow = now.strftime('%Y-%m-%d')#日期,精确到天
#将当前时间写入intime变量中
user.intime = myNow
user.save()
return HttpResponse('upload ok!')
else:
uf = UserForm()
return render_to_response('upload.html',{'uf':uf})
5、urls文件配置
6、配置setting文件
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/helloworld/blog/templates'
) #MEDIA_ROOT是用户上传的文件存储的位置,是文件系统上的路径,
#FileField, ImageField里面的upload_to的相对路径就是相对于MEDIA_ROOT的。
MEDIA_ROOT = 'C:/djangoweb/helloworld/upload' # URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/upload/'
7、修改upload.HTML
<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" >
{{uf.as_p}}
<input type="submit" value="ok"/>
</form> </body>
</html>