In my edit.html I have a form where the user can edit information on a trainee. The user can add many trainees, edit them, delete them etc. Everything works fine there except the image. The imagefield of form appears in a very messy state. Also it does not update when I select a new image. Here is my code. I have cut down my code to make it more readable
models.py
class Trainee(models.Model):
TraineePic = models.ImageField(null=True, blank= True, upload_to="traineeImg/")
Name = models.CharField(max_length=50)
class Meta():
db_table = "Trainee"
forms.py
class TraineeForm(forms.ModelForm):
TraineePic = forms.ImageField(label="Image :", required=False)
Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :')
class Meta():
model = Trainee
fields = ("Name","TraineePic",)
views.py
class UpdateTrainee(UpdateView):
model = Trainee
template_name = 'MyTestApp/edit.html'
form_class = TraineeForm
success_url = reverse_lazy('show')
edit.html
{% extends "MyTestApp/base.html" %}
{% block body_block %}
{% load static %}
<link rel="stylesheet" href="{% static '/css/bootstrap.min.css'%}" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<style>
ul#id_Gender li{
display: inline-block;
}
</style>
<body>
<div >
<h2> Edit Trainee </h2>
<form method="post" type="multipart/form-data" data-ajax="false">
{%csrf_token%}
{{form.errors}}
<div >
<label >{{ form.TraineePic.label }}</label>
{{form.TraineePic}}
</div>
<div >
<label >{{ form.Name.label }}</label>
{{ form.Name }}
</div>
<input type="submit" value="Update" >
</form>
</div>
</body>
{% endblock %}
Here is how the form.TraineePic looks like:
I also tried adding FileInput like this TraineePic = forms.ImageField(label="Image :", required=False,widget=forms.FileInput) But then I don't get any image. Any help would be appreciated.
CodePudding user response:
You must use #request.FILES to get image from frontend to backend and make it successfully save on database.
In views.py
Example:
Trainee_Pic= self.request.FILES.get('TraineePic') # Use request.FILES
CodePudding user response:
I found the solution. Looks like there was a typo in my form in edit.html I changed my form from
form method="post" type="multipart/form-data" >
to
form method="post" enctype="multipart/form-data" >
And the image field in form which looked very bad previously, I put it in a div with style='display: inline-block' so now it looks pretty ok.