I am trying to have a Django Model form with an image field but I have the two problems:
- I don't know how to show the current name of the image in the input
- I don't know how to provide a way to remove the image
forms:
class CityLogoForm(forms.ModelForm):
logo = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'}), required=False)
class Meta:
model = City
fields = ['logo']
views:
def management_form_general(request, city_slug):
city = City.objects.get(slug=city_slug)
if request.method == 'POST':
logo_form = CityLogoForm(request.POST, request.FILES, instance=city)
if logo_form.is_valid():
logo_form.save()
else:
logo_form = CityLogoForm(instance=city)
return render(request, 'management/form/city_general.html', {'city': city, 'logo_form': logo_form})
html:
<form action="" enctype="multipart/form-data" method="post">
<div class="form-group row">
<label for="id_city" class="col-sm-2 col-form-label form_title">{{ logo_form.logo.label }}</label>
<div class="custom-file">
{{ logo_form.logo }}
<label class="custom-file-label" for="{{ logo_form.logo.id_for_label }}" data-browse="Choisir Image">{{ logo_form.logo.label }}</label>
</div>
</div>
</form>
I have a script changing the label when the user is uploading something but I cannot find a way to get the current value for the image fields (for the normal ones it's properly prepopulated). As it seems to not prepopulate the input, it seems to be ignoring when the input is empty and therefore never deletes the current logo.
Edit : if possible the answer need to be doable in a for loop over a formset_factory