1

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...

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.