视图部分:
需要注意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 =