django image upload help
I have a template where the user can input data about himself, and upload his photo. Photo uploading will be done using ajax, with a separate upload button inside the form. My question is how do I 开发者_JS百科upload the photo (when the user clicks on the upload button) and then save the user info when the user clicks on the submit button.
The model looks like this:
class User(models.Model):
name = models.CharField(max_length=50)
# some other fields
image = models.ImageField(upload_to="assets/images")
Thanks!
You could return the id of the User instance you used to save the picture as part of your js callback/success function, use it to populate a hidden field, and then call that user instance and save the rest of the info when the user submits the form.
The bigger question is, especially given that the user is going to submit the form anyway, why do you want to save just the image first?
You would need to use an <input type="button" />
with a JavaScript event handler to process the upload. jQuery's $.POST can do this very easily for you.
If you use an <input type="submit" />
for the image upload, it will also submit its containing form.
You will probably want to disable the actual "save" button until the ajax process has finished and that record has been saved, in case you need to make any associations to other data from your form, etc.
Hope that gets you going.
精彩评论