Reputation: 103
I would like to upload a profile picture with ajax.
But even if I don´t send the image with ajax, it doesn´t work.
I have the following code in my website:
<form action="{% url 'update_profile_pic' %}" method="post">
{% csrf_token %}
<input name="profilePic" type="file" accept="image/*"/>
</form>
The profilePic should be saved in the model:
class UserProfile(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key=True,
)
profilePic = ProcessedImageField(
upload_to=generate_random_filename,
processors=[ResizeToFill(150, 150)],
format='JPEG',
options={'quality': 60},
)
...
The url.py has the correct entry:
...
path('update_profile_pic/', views.UpdateProfilePic.as_view(), name='update_profile_pic'),
...
The form is like this:
class ProfilePicForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('profilePic',)
And the view should also be correct:
class UpdateProfilePic(View):
def post(self, request):
form = ProfilePicForm(self.request.POST, self.request.FILES)
if form.is_valid():
request.user.userprofile.profilePic = form.cleaned_data['profilePic']
request.user.userprofile.save()
return JsonResponse({
image_url : request.user.userprofile.profilePic.url
})
else:
raise Http404(form.errors)
But I always get the error "profilePic This field is required.", when I upload a picture. This error comes from the raise Http404(form.errors)
, so the form is not valid.
When I look at the headers in the network tab in google chrome, it shows me this:
csrfmiddlewaretoken: sbyaJ8J7COSdC0OUYr4p8ToaarjFrIniDKLT3Lr36PVeTUlc9MEafr77exYVvkXL
profilePic: fr.cc38d01b0b77.gif
What do I do wrong here?
Upvotes: 0
Views: 686
Reputation: 568
multipart is defined for supporting file format. So if you do not specify this model then the form is not able to support any kind of file format. Like if you need to upload a pdf file or a video file or an image file, for any kind of file the model form is needed in order to know you want to upload a file, because of security.
If you need just data anyone can upload or try to do something not allowed
***<form action="{% url 'update_profile_pic' %}" method="post" enctype="multipart/form-data">***
Upvotes: 1
Reputation: 3371
Change form to:
<form action="{% url 'update_profile_pic' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input name="profilePic" type="file" accept="image/*"/>
</form>
You missed enctype="multipart/form-data"
.
If you face any issue regarding backend then this documnet will help you.
Upvotes: 2