form表单上传文件
例如注册页面上传头像
html创建
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/dist/css/bootstrap.css">
<script src="/static/dist/js/jquery-3.2.1.js"></script>
<script src="/static/dist/js/bootstrap.js"></script>
<link rel="stylesheet" href="/static/css/login.css">
<style>
#avatar{
position: relative;
width: 60px;
height: 60px;
}
#avatar_img,#file{
width: 60px;
height: 60px;
position: absolute;
left: 60px;
top:0;
}
#file{
opacity: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<form class="col-md-6 col-md-offset-2">
{% csrf_token %}
<div class="form-group">
<label for="user">用户名</label>
{{ regForm.username }} <span class="error"></span>
</div>
<div class="form-group">
<label for="pwd">密码</label>
{{ regForm.password }} <span class="error"></span>
</div>
<div class="form-group">
<label for="pwd">确认密码</label>
{{ regForm.repeat_password }} <span class="error"></span>
</div>
<div class="form-group">
<label for="pwd">邮箱</label>
{{ regForm.email }} <span class="error"></span>
</div>
<div class="form-group" id="avatar">
<label for="pwd">头像</label>
<p><img src="/static/img/default.png" alt="" id="avatar_img"></p>
<p><input type="file" id="file"></p>
</div>
<div class="row">
<div class="col-md-6">
<input type="button"value="注册提交" class="btn btn-primary regBtn"><span class="error"></span>
</div>
</div>
</form>
</div>
</div>
<script>
$(".regBtn").click(function () {
var formdata=new FormData();
formdata.append("username",$("#id_username").val());
formdata.append("password",$("#id_password").val());
formdata.append("repeat_password",$("#id_repeat_password").val());
formdata.append("email",$("#id_email").val());
formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val());
formdata.append("avatar",$("#file")[0].files[0]);
$.ajax({
url:"/reg/",
type:"post",
data:formdata,
contentType:false,
processData:false,
success:function (data) {
var data=JSON.parse(data);
//console.log(data);
if(data.user){
location.href="/login/"
}
else {
var error_dict=data.error_msg ; // {"username":["asda"],"email":["asdsa"]}
$(".error").html("");
$.each(error_dict,function (i,j) {
console.log(i,j);
$("#id_"+i).next().addClass("pull-right").html(j[0]).css("color","red")
if(i=="__all__"){
$("#id_repeat_password").next().html(j[0])
}
})
}
}
})
})
// 预览功能
$("#file").change(function () {
var choose_file=$("#file")[0].files[0];
var reader=new FileReader();
reader.readAsDataURL(choose_file);
reader.onload=function () {
$("#avatar_img").attr("src",this.result)
}
})
</script>
</body>
</html>
创建注册类
def reg(request):
if request.is_ajax():
regForm=RegForm(request.POST)
regResponse={"user":None,"error_msg":None}
if regForm.is_valid():
username=regForm.cleaned_data.get("username")
password=regForm.cleaned_data.get("password")
email=regForm.cleaned_data.get("email")
avatar=request.FILES.get("avatar")
print(regForm.cleaned_data,"------")
user=UserInfo.objects.create_user(username=username,password=password,email=email,avatar=avatar)
regResponse["user"]=user.username
else:
regResponse["error_msg"]=regForm.errors # errors只存错误字段
return HttpResponse(json.dumps(regResponse))
regForm=RegForm()
return render(request,'reg.html',locals())
model里用户信息表
class UserInfo(AbstractUser):
"""
用户信息
"""
nid = models.AutoField(primary_key=True)
nickname = models.CharField(verbose_name='昵称', max_length=32)
telephone = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')
avatar = models.FileField(verbose_name='头像', upload_to='avatarDir/', default="avatar/default.png")
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
blog = models.OneToOneField(to='Blog', to_field='nid', null=True)
def __str__(self):
return self.username
setting里需要设置路径
AUTH_USER_MODEL = "blog.UserInfo"
MEDIA_ROOT=os.path.join(BASE_DIR,"blog","media")
MEDIA_URL="/media/"