python-django文件上传

视图部分:

需要注意enctype="multipart/form-data"

<!DOCTYPE html>
<html>
<head>
	<title>title</title>
</head>
<body>
	<div>注册</div>
	<form method="post" enctype="multipart/form-data">
		{{uf.as_p}}
		<input type="submit" value="ok">
	</form>
</body>
</html>


逻辑处理:

# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django import forms

class UserForm(forms.Form):
	username = forms.CharField()
	headImg = forms.FileField()

def register(req):
	if req.method == "POST":
		uf = UserForm(req.POST,req.FILES)
		if uf.is_valid():
			print uf.cleaned_data['username']
			print uf.cleaned_data['headImg'].name
			print uf.cleaned_data['headImg'].size
			fp = file(uf.cleaned_data['headImg'].name+'1','wb')
			s = uf.cleaned_data['headImg'].read()
			fp.write(s)
			fp.close()
			return HttpResponse('ok')
	else:
		uf = UserForm()
	return render_to_response('register.html',{'uf':uf})



通过数据库上传:

开启后台上传测试:

from django.db import models

# Create your models here.

class User(models.Model):
	username = models.CharField(max_length=30)
	headImg = models.FileField(upload_to='./upload/')

	def __unicode__(self):
		return self.username
记得注册blog里面的user:

from django.contrib import admin
from blog.models import User

admin.site.register(User)

settings里面设置上传路径:MEDIA_ROOT = 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值