Home > front end >  Django "ImageField" form value is None
Django "ImageField" form value is None

Time:03-16

I'm trying to implement profile picture field for users. The following is the code for each file for the implementation I tried, forms.py, models.py, views.py, and urls.py.

I use a IDE (vscode) to debug django, and I placed a breakpoint on the user.avatar = form.cleaned_data['avatar'] line in views.py below, to quickly check if cleaned_data['avatar'] is filled as user input, as I expect.

However, even after I upload a file on the url, submit, the line shows None while expected a image object, and of course it doesn't save anything so no change to the database either.

# 
# forms.py 
# accounts/forms.py
# 

from accounts.models import UserProfile

# .. 

class UserProfileForm(forms.ModelForm):

    avatar = forms.ImageField(label=_('Avatar'))

    class Meta:
        model = UserProfile
        
        fields = [
            'avatar',
        ]

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        self.fields['avatar'].required = False

# 
# models.py
# accounts/models.py
# 

from django.contrib.auth.models import User
from PIL import Image 

class UserProfile(models.Model):
    user   = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to="images", blank=True, null=True)

# note: I also did "python manage.py makemigrations accounts; python manage.py migrate accounts;"

# 
# views.py
# accounts/views.py
# 

class UserProfileView(FormView):
    template_name = 'accounts/profile/change_picture.html'
    form_class = UserProfileForm

    def form_valid(self, form):
        user = self.request.user
        user.avatar = form.cleaned_data['avatar']
        user.save()
        
        messages.success(self.request, _('Profile picture has been successfully updated'))

        return redirect('accounts:change_profile_picture')

# 
# urls.py
# accounts/urls.py
# 

from .views import UserProfileView

urlpatterns = [
    # ..
    path('change/profile_picture/', UserProfileView.as_view(), name='change_profile_picture'),
]


What is wrong with the code? Thanks.

edit

as requested, the html accounts/profile/change_picture.html

{% extends 'layouts/html.html' %}

{% load static %}
{% load bootstrap4 %}
{% load i18n %}

{% block content %}

{% include 'head.html' %}

<body>
    
    {% include 'navbar.html' %}

    <div id="content" name="content" >
        <div ></div>

        <h2>{% trans 'Change profile picture' %}</h2>
        
        <form method="post">
        
            {% csrf_token %}
            {% bootstrap_form form %}
        
            <button >{% trans 'Change' %}</button>
        
        </form>

        <div ></div>        
    </div>

    {% include 'footer.html' %}  

</body>

{% endblock %}

CodePudding user response:

<form method="post" enctype="multipart/form-data">
        
  {% csrf_token %}
  {% bootstrap_form form %}
        
  <button >{% trans 'Change' %}</button>
        
</form>
  • Related