Проблема сохранения изображений в Django

VIEWS.PY

def Profile(request):
if request.method == "POST":
    profile = UserForm(request.POST, request.FILES, instance=request.user)
    if profile.is_valid():
        profile.save()
    return redirect("Profile")
profile = UserForm(instance=request.user)
return render(request, "book/Profile.html", context={"user": request.user, "profile": profile})

FORMS.PY

class UserForm(forms.ModelForm):
username = forms.CharField(max_length=50, label='Username', widget=forms.TextInput(attrs={"class": "form-control"}))
email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={"class": "form-control"}))
first_name = forms.CharField(max_length=50, required=False, label='First name', widget=forms.TextInput(attrs={"class": "form-control"}))
last_name = forms.CharField(max_length=50, required=False, label='Last name', widget=forms.TextInput(attrs={"class": "form-control"}))
avatar = forms.ImageField(required=False, widget=forms.FileInput(attrs={"class": "form-control"}))

class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name', 'email', 'avatar')

MODELS.PY

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='UserAvatar/%Y/%m/%d/', blank=True)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
   if created:
      Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
   instance.profile.save()

PROFILE.HTML

         <div class="modal-body">
                <form method="post" enctype="multipart/form-data">

                    {% csrf_token %}
                    {{ profile }}

                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save changes</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </form>
            </div>

У меня возникла проблема. Я новичок в Django и недавно загрузил изображение из forms.Form, но теперь я использую forms.ModelForm и не совсем понимаю, в чем проблема. Что я делаю не так?

Вернуться на верх