model:
class Logo(models.Model):
media = models.ImageField(upload_to='uploads')
def __unicode__(self):
return self.media.url
view:
class LogoEdit(UpdateView):
model = Logo
template_name = 'polls/logo-edit.html'
success_url = '/polls/logos/'
def form_valid(self, form):
pdb.set_trace()
template:
<form id="my_form" action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save Changes" />
</form>
selecting new image:
form
debug view:
existing image:
(Pdb) self.object
<Logo: media/uploads/DSCN0844.JPG>
form with new selected image (DSC_0021.JPG):
(Pdb) test = form.save()
(Pdb) test
<Logo: media/uploads/DSCN0844.JPG>
As you can see the original image remains in form!
If you are using UpdateView
, you only need to add enctype="multipart/form-data"
attribute to the form tag in your template. The rest will be handled by UpdateView
class.
just add to your template
<form method="POST" enctype="multipart/form-data">
You need to save the form providing request.FILES:
if request.method == 'POST':
form = MyForm(request.POST, request.FILES)
if form.is_valid():
form.save()
And in your HTML form (since you have an <input type="file">
in the form):
<form method="POST" enctype="multipart/form-data">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With