Reputation:
I am new Django and am creating a social network website to get my hands on it. I have made a form for uploading profile picture and successfully rendered in my template but when I am uploading it I am getting an error named profile_pic. Please help me out with this.
views.py - This is the processing that I am doing. I get here an invalid form error and the line return HttpResponse(profilePicForm.errors) returns profile_pic as response.
if request.method == "POST":
profilePicForm = ProfilePicForm(request.POST, request.FILES)
if profilePicForm.is_valid():
return HttpResponse("<h1>Valid</h1>")
profilePic = ProfilePictures()
query = UserInfo.objects.filter(id=id)
for user in query:
profilePic.user = user
break
profilePic.profile_pic = profilePicForm.cleaned_data['profile_pic']
profilePic.save()
return redirect('newsfeed:profile')
else:
return HttpResponse(profilePicForm.errors)
forms.py - The form class
class ProfilePicForm(forms.Form):
profile_pic = forms.FileField()
profile.html - This is how I am rendering it.
<form action="{% url 'newsfeed:uploadProfilePic' %}" method="post">
{% csrf_token %}
{{ profilePicForm.as_p }}
<button type="submit">Upload</button>
</form>
Upvotes: 3
Views: 556
Reputation: 47374
It's common practice to render same template if form is not valid, to see error messages on the web page, so instead of return HttpResponse(profilePicForm.errors)
you shoud do something like this:
if profilePicForm.is_valid():
return HttpResponse("<h1>Valid</h1>")
profilePic = ProfilePictures()
query = UserInfo.objects.filter(id=id)
for user in query:
profilePic.user = user
break
profilePic.profile_pic = profilePicForm.cleaned_data['profile_pic']
profilePic.save()
return redirect('newsfeed:profile')
else:
return render(request, 'template.html', {'profilePicForm': profilePicForm})
Also for file uploading you should add to the form enctype="multipart/form-data"
:
<form action="{% url 'newsfeed:uploadProfilePic' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ profilePicForm.as_p }}
<button type="submit">Upload</button>
</form>
Upvotes: 2