I tried updating a user's profile picture using a function view (ajax) but I keep getting the error below:
raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'emp_photo'
The same technique I am using is being used on CharField and TextField without issues.
Please see below for my codes.
views.py
@login_required(login_url='/login/')
@user_passes_test(user_type_combo)
def change_employee_photo(request, pk):
data = dict()
profile = get_object_or_404(Profile, pk=pk)
if request.method == 'POST':
form = EmployeePhotoForm(request.POST or None, request.FILES or None, instance=profile)
if form.is_valid():
newPic = profile(emp_photo=request.FILES['emp_photo'])
newPic.save()
data['is_valid'] = True
else:
form = EmployeePhotoForm(instance=profile)
data['form_is_valid'] = False
context = {
'form': form,
}
data['html_form'] = render_to_string('employees/partial_employee_photo.html',
context,
request=request
)
return JsonResponse(data)
forms.py
class EmployeePhotoForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['emp_photo',]
{% load crispy_forms_tags %}
<form action="{% url 'change_employee_photo' form.instance.pk %}" class="js-change-employee-photo-form"
enctype="multipart/form-data" id="ProfileUpdateForm" method="post" runat="server">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title">Change Employee Photo</h5>
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group col">
<div id="emp_photo_holder">
<img alt="{{profile.first_name}}_{{profile.last_name}}" height="200px" id="emp_img"
src="/media/default.jpg/" width="200px"/>
<input id="emp_photo" name="emp_photo" type="file" value="{{profile.emp_photo}}"/>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#emp_img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#emp_photo").change(function() {
readURL(this);
});
</script>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" type="button">Close</button>
<button class="btn btn-warning confirmation"
onclick="return confirm('Are you sure you want upload a new photo for this employee?')"
type="submit">
<i class="fa fa-upload"></i> Upload
</button>
</div>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
I will most definitely appreciate any help to have this issue resolved.