Reputation: 1980
form 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)
...
and 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/'
when I use the django admin page, the image will load and save: http://training-hongquan156.dotcloud.com/media/avatar/image.png but when I use html form upload photos, the image is not uploaded and saved in the folder 'avatar', but saves the path: http://training-hongquan156.dotcloud.com/media/image.png and i can't load image... what's problem?
Upvotes: 0
Views: 2533
Reputation: 12921
You should correct
<form action="/register/" method="post">
to
<form action="/register/" enctype="multipart/form-data" method="post">
handle the uploaded file with
request.FILES['avatar']
then find it in dir $upload_to
,/home/dotcloud/data/media/photo
Upvotes: 4