Can't Upload Image Field With Django 2.1

154 views
Skip to first unread message

Pacôme Avahouin

unread,
Oct 30, 2018, 10:38:38 PM10/30/18
to Django users
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.

Tim Graham

unread,
Oct 31, 2018, 9:51:12 AM10/31/18
to Django users
It would be helpful to see the complete traceback. What you provided doesn't show where the exception originates.

Pacôme Avahouin

unread,
Oct 31, 2018, 10:28:42 AM10/31/18
to Django users
Hello Tim,

Thanks for answering.

Here is the complete traceback.
By the way when i commented out the 'upload_file' function still i'm getting the same error. 
I believe the origin might be somewhere else.



Environment:


Request Method: POST

Django Version: 2.1.2
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrap4',
 'accounts',
 'posts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\core\handlers\base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\views\generic\base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\utils\decorators.py" in _wrapper
  45.         return bound_method(*args, **kwargs)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "D:\ISMAEL\APPS\EMX\emlaxpress\accounts\views.py" in dispatch
  36.         return super().dispatch(*args, **kwargs)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\views\generic\base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\views\generic\edit.py" in post
  194.         return super().post(request, *args, **kwargs)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\views\generic\edit.py" in post
  141.         if form.is_valid():

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\forms\forms.py" in is_valid
  185.         return self.is_bound and not self.errors

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\forms\forms.py" in errors
  180.             self.full_clean()

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\forms\forms.py" in full_clean
  383.         self._post_clean()

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\forms\models.py" in _post_clean
  398.             self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\forms\models.py" in construct_instance
  63.         f.save_form_data(instance, cleaned_data[f.name])

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\db\models\fields\files.py" in save_form_data
  317.             setattr(instance, self.name, data or '')

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\utils\functional.py" in __setattr__
  244.             setattr(self._wrapped, name, value)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\db\models\fields\files.py" in __set__
  346.             self.field.update_dimension_fields(instance, force=True)

File "C:\Users\ATM\Anaconda3\envs\EmXp\lib\site-packages\django\db\models\fields\files.py" in update_dimension_fields
  434.             (self.width_field and not getattr(instance, self.width_field)) or

Exception Type: TypeError at /user/edit-profile/
Exception Value: getattr(): attribute name must be string
 

Tim Graham

unread,
Oct 31, 2018, 10:33:43 AM10/31/18
to Django users
It looks like the width_field option on the model field isn't a string.

Pacôme Avahouin

unread,
Oct 31, 2018, 10:53:53 AM10/31/18
to Django users
Tim you just saved me right now:) I have spent the all night trying to figure it out.
Thanks a lot.
Now when i removed the width_field it works fine. But how to define height_field and width_field directly from the model?
Cause when i put their values in quotes i got another error.

Tim Graham

unread,
Oct 31, 2018, 11:18:01 AM10/31/18
to Django users
height_field and width_field should be strings. What's the error and what does your model fields look like?

Pacôme Avahouin

unread,
Oct 31, 2018, 11:44:17 AM10/31/18
to Django users
My model fields look like this:

class CustomAbstractUser(AbstractBaseUser, PermissionsMixin):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    Email and password are required. Other fields are optional.
    """
    email = models.EmailField(
        _('email address'),
        unique=True,
        error_messages={
            'unique': _("A user with that email address already exists."),
        },
    )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=150, blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    phone_number = models.PositiveSmallIntegerField(null=True, blank=True)
    current_title = models.CharField(max_length=30, blank=True)
    website_url = models.URLField(blank=True)
    avatar = models.ImageField(upload_to='accounts/%Y/%m/%d',
                               height_field='160', width_field='160',
                               max_length=100, null=True, blank=True
                               )

    objects = CustomUserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'


And this is the traceback:



Environment:


Request Method: POST

Exception Type: AttributeError at /user/edit-profile/
Exception Value: 'CustomUser' object has no attribute '160' 


Really Appreciate the help

Tim Graham

unread,
Oct 31, 2018, 11:55:30 AM10/31/18
to Django users
You've misunderstood the purpose of height_field and width_field. Please read the documentation: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ImageField.height_field

You need to use a third-party app to do image resizing. Check out https://djangopackages.org/grids/g/thumbnails/.

Pacôme Avahouin

unread,
Oct 31, 2018, 12:06:01 PM10/31/18
to Django users
Yes you right Tim, i have misunderstood the purpose of height_field and width_field, i'm new in Django :)
Gonna check more in the documentation and try a third-party app to resize images.
Thanks a lot for the help. I appreciate.
Reply all
Reply to author
Forward
0 new messages