mursalin
mursalin

Reputation: 1181

upload file using django form

Can anyone help me find my mistake.I am new to django.I want to upload a image using form.

#forms.py
class ProfileFormSt(forms.Form):
     image_url = forms.FileField(required=False)

#views.py
class UpdateProfileStView(FormView):
    template_name = "home/member_st_form.html"

    def get(self, request, id):
        user = User.objects.get(id=self.kwargs['id'])
        profile = StudentProfile.objects.get(user=user)
        form = ProfileFormSt(initial={
            'image_url': profile.propic,
        })
        return render(request, self.template_name, {'form': form})

    def post(self, request, id):
        user = User.objects.get(id=self.kwargs['id'])
        form = ProfileFormSt(request.POST, request.FILES)
        profile = StudentProfile.objects.get(user=user)
        if request.POST.get('image_url'):
            profile.propic = request.POST.get('image_url')
        profile.save()
        return redirect('home:member-profile-st', id)

#member_st_form.html
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }}
    <button type="submit">update</button>
</form>

#models.py
class StudentProfile(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      propic = models.FileField(default="profile-icon.png")

request.POST.get('image_url') always returns empty...cant find what I did wrong...

Upvotes: 1

Views: 43

Answers (1)

Bipul Jain
Bipul Jain

Reputation: 4643

Your image_url is a file field, so it should be present in request.FILES

if request.FILES['image_url']:
     profile.propic = request.FILES['image_url']

Upvotes: 1

Related Questions