Tuesday, October 30, 2018

Can't Upload Image Field With Django 2.1

Hello guys, 

I'm trying to upload user avatar (ImageField type) with my own custom user model following the documentation like this:

class MyUsersProfileView(UpdateView):

# First try
def upload_file(request):
    if request.method == 'POST':
        form = MyModelFormWithFileField(request.POST, request.FILES)
        if form.is_valid():
            # file is saved
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = MyModelFormWithFileField()
    return render(request, '/my-model-form-with-the-upload-field.html', {'form': form})

# Second try
def upload_file(request):
    if request.method == 'POST':
        form = MyUploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            instance = MyModelFormWithFileField(file_field=request.FILES['file'])
            instance.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = MyUploadFileForm()
    return render(request, 'my-model-form-with-the-upload-field.html', {'form': form})


but i'm always getting the same error:

TypeError at /user/edit-profile/  getattr(): attribute name must be string  Request Method:	POST  Request URL:	http://127.0.0.1:8000/user/edit-profile/

All other fields got updated but not the profile picture.
I have tried everything but couldn't figure it out.
Any help would be appreciate.
Thanks in advance.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/cca2d504-e131-4198-b83d-bc1f4142e958%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment