0

表单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>

模型.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}))

设置.py

MEDIA_ROOT = '/home/dotcloud/data/media/'
MEDIA_URL = '/media/'

当我使用 django 管理页面时,图像将加载并保存: http : //training-hongquan156.dotcloud.com/media/avatar /image.png 但是当我使用 html 表单上传照片时,图像没有上传和保存在文件夹“头像”中,但保存路径: http ://training-hongquan156.dotcloud.com/media/image.png 并且我无法加载图像...有什么问题?

4

1 回答 1

4

你应该纠正

<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

于 2012-06-21T10:18:37.323 回答