表格html:
<form action='/register/' method = 'post'>{% csrf_token %}
...
<label>Avatar: </label><input type='file' name='avatar' value='' /><br />
<input type = 'submit' name='submit' value='Sign up' />
</form>
models.py
class Employee(models.Model):
...
avatar = models.ImageField(upload_to = 'avatar', blank = True, null = True)
...
和views.py
def register(request):
success = False
message = ''
try:
newE = Employee.objects.create(...
avatar = request.POST['avatar'])
success = True
message = 'Register successful!'
return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}))
except:
Employee.objects.filter(email = request.POST['email']).delete()
message = 'Can\'t create a new account!'
return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}))
settings.py
MEDIA_ROOT = '/home/dotcloud/data/media/'
MEDIA_URL = '/media/'
当我使用django管理页面时,图像将加载并保存: http://training-hongquan156.dotcloud.com/media/的化身 /image.png 但是当我使用html表格上传照片时,图片不会上传并保存在“ 头像 ”文件夹中,但会保存路径: http://training-hongquan156.dotcloud.com/media/image.png 我无法加载图片... 什么问题?
答案 0 :(得分:3)
你应该纠正
<form action="/register/" method="post">
到
<form action="/register/" enctype="multipart/form-data" method="post">
使用
处理上传的文件request.FILES['avatar']
然后在dir $upload_to
,/home/dotcloud/data/media/photo