Reputation: 1370
I'm currently working on a customized admin page on my site where users will be allowed to update their profile page. I have several fields including an image field for profile images... I have then created a EditProfileForm to deal with this action. I've learned about serializing the form within the Ajax request to post the form data to server side. I have this working for other forms that doesn't have a file field, and it works perfectly. But somehow, it's just not working for this form with the image field.
forms.py
class EditProfileForm(forms.Form):
avatar = forms.ImageField(widget=forms.ClearableFileInput(attrs=edit_profile_form_fields['avatar']), label='Change Profile Image')
mobile = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['mobile']), label='Mobile Number', required=False)
street = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['street']), label='Street', required=False)
city = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['city']), label='City', required=False)
state = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['state']), label='State', required=False)
country = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['country']), label='Country', required=False)
about = forms.CharField(widget=forms.Textarea(attrs=edit_profile_form_fields['about']), label='About Me', required=False)
def clean_mobile(self):
if Account.objects.filter(mobile=self.cleaned_data['mobile']).exists() and len(self.cleaned_data['mobile']) > 0:
raise forms.ValidationError('Mobile already exists!')
return self.cleaned_data['mobile']
def save(self, user_id):
account = Account.objects.get(user_id=user_id)
account.avatar = self.cleaned_data['avatar']
account.mobile = self.cleaned_data['mobile']
account.street = self.cleaned_data['street']
account.city = self.cleaned_data['city']
account.state = self.cleaned_data['state']
account.country = self.cleaned_data['country']
account.about = self.cleaned_data['about']
account.save()
In my html I have...
<form id="edit-profile-form" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="avatar">
{{ edit_profile_form.avatar.label }}
</label>
{{ edit_profile_form.avatar }}
</div>
<div class="form-group">
<label for="mobile">
{{ edit_profile_form.mobile.label }}
<span class="mobile-exist text-danger" style="display: none;"></span>
</label>
{{ edit_profile_form.mobile }}
</div>
<div class="form-group">
<label for="street">
{{ edit_profile_form.street.label }}
</label>
{{ edit_profile_form.street }}
</div>
<div class="form-group">
<label for="city">
{{ edit_profile_form.city.label }}
</label>
{{ edit_profile_form.city }}
</div>
<div class="form-group">
<label for="country">
{{ edit_profile_form.country.label }}
</label>
{{ edit_profile_form.country }}
</div>
<div class="form-group">
<label for="about">
{{ edit_profile_form.about.label }}
</label>
{{ edit_profile_form.about }}
</div>
<div class="d-flex align-items-center">
<button type="submit" class="btn btn-outline-warning px-3" id="edit-profile-submit-btn">
Update Profile <span class="btn-icon-right"><i class="fa fa-save"></i></span>
</button>
<button type="reset" class="btn btn-outline-primary px-3 ml-3" id="edit-profile-reset-btn">
Reset <span class="btn-icon-right"><i class="fa fa-refresh"></i></span>
</button>
<button type="button" class="btn btn-outline-danger px-3 ml-3" id="edit-profile-div-close">
Cancel <span class="btn-icon-right"><i class="fa fa-times"></i></span>
</button>
</div>
</form>
In my js where I do the Ajax call, I have...
var csrfmiddlewaretoken = $("#edit-profile-form").find("input[name='csrfmiddlewaretoken']").val();
var form_data = $('#edit-profile-form').serialize();
$.ajax({
type: 'POST',
url: '/edit-profile/',
dataType : "json",
data : {
csrfmiddlewaretoken: csrfmiddlewaretoken,
form_data: form_data,
},
success: function (data){
console.log('Success');
},
error: function (){
console.log('Error');
}
});
Now within my views that handles this post request, I have...
class EditProfileView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard/pages/profile.html'
form_class = EditProfileForm
def post(self, request, *args, **kwargs):
from django.http import QueryDict #To basically de-serialize the serialized form passed by the Ajax request
new_form_data = QueryDict(request.POST['form_data'].encode('ASCII'))
#From the new form data (QueryDict Obj), I will set a dict.
data = {
'avatar': new_form_data.get('avatar'),
'mobile': new_form_data.get('mobile'),
'street': new_form_data.get('street'),
'city': new_form_data.get('city'),
'state': new_form_data.get('state'),
'country': new_form_data.get('country'),
'about': new_form_data.get('about'),
}
#Passing data dict as an argument to initialize the form
form = self.form_class(data)
if form.is_valid():
print('Form is valid')
else:
print('Form is not valid')
I have tried printing the data dict which I have create but 'avatar' is none. Here's an example...
The result from printing the data...
So even though I have uploaded the image, it has not been passed as part of the form data from the Ajax request. I have been researching but yet to find a similar problem that has a solution. Looking forward to getting some help from you wonderful people soon.
Upvotes: 1
Views: 510
Reputation: 1370
I found a solution! I used FormData
to package up the data from my edit profile form then append the image field to that FormData
then submit it. Submitted a bit different from the methods I've used when dealing without files though.
Update in my js...
var form = $("#edit-profile-form")[0];
var form_data = new FormData(form);
// Appending the attached file to the form_data to access it from the server side
form_data.append('new_avatar', $("#avatar")[0].files[0]);
$.ajax({
type: 'POST',
url: '/edit-profile/',
data: form_data,
cache: false,
processData: false,
contentType: false,
success: function (data){
console.log('Success');
},
error: function (){
console.log('Error');
}
});
Then in my views, I would just initialize the form in a normal manner without any de-serialization.
def post(self, request, *args, **kwargs):
context = {}
form = self.form_class(data=request.POST, files=request.FILES)
if form.is_valid():
print('Form is valid')
else:
print('Form is not valid')
return JsonResponse(context)
This did the job for me... Sweet and nice! :-)
Upvotes: 2