1👍
Mm interesting question Adriano. You can access the image using the instance
attribute of the form
. Assume that you have a edit
view function that accept the pk
and passing the form as the context like this…
def edit(request, pk):
user = User.objects.filter(pk=pk).first()
if request.method == "POST":
pass
return HttpResponseRedirect(reverse("edit", args=[pk]))
form = UserForm(instance=user)
return render(request, "index.html", {"form": form})
As I have mentioned now it’s very easy to access the photo attribute in the template like this {{ form.instance.photo }}
<div id="updateImageHere"></div>
<script>
const decodedImageString = "{{ form.instance.photo.decode }}";
var image = new Image();
image.src = `data:image/png;base64,${decodedImageString}`;
const updateImageHere = document.getElementById("updateImageHere")
updateImageHere.appendChild(image);
</script>
I have assigned decoded photo to constant and then user the image.src to append into the updateImagehere div. Let me know if you have any questions…
0👍
If your issue is to display the image before the form has been submitted, you need to use javascript.
Example
$('your_file_input_field').change(function() {
src = URL.createObjectURL($(this).prop('files')[0]);
$('your_image_container').attr("src", src);
}
If you want to display an image that has been binary-coded (that is, after it has been saved to your database), refer to this discussion (https://stackoverflow.com/questions/55886078/).
In general it’s not a good idea to save the image in your database as binary, unless you have a specific reason to do so. Instead, just use a file field to save the image, which will then refer to the respective file in your server dir structure.
- [Answered ]-Django high memory usage
- [Answered ]-How send value from view to template form url
- [Answered ]-Should I include translation correctness in functional testing?
- [Answered ]-Can i use an other language instead of english for default django translation