简体   繁体   中英

Django "ImageField" form value is None

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" class="main container">
        <div class="w-100 p-3"></div>

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

        <div class="w-100 p-3"></div>        
    </div>

    {% include 'footer.html' %}  

</body>

{% endblock %}

Add enctype="multipart/form-data" to the form:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM