Django 图片上传错误,"This field is required', "没有选择文件”

Django image uploading error, "This field is required', "no files chosen"

我正在做一个 django 项目。我制作了一个 userprofiles 应用程序来管理(创建、更新)我网站上的用户个人资料,但它无法正常工作。我收到 'This field is required' & 'no file chosen' 作为用户创建个人资料时,如果我在模型中做 blank=True profile_picture 用户图片不会保存在媒体中 url。 我已经尝试了很多来自 Whosebug 的提示,但它们没有用。 这是我的代码:

# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('media'))

# models.py
from django.db import models
from django.contrib.auth import get_user_model
import uuid


class UserProfile(models.Model):
   author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
   profile_picture = models.ImageField(upload_to='images/')
   id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
   bio = models.TextField(blank=True)
   occupation = models.CharField(max_length=100)
   hobbies = models.TextField(blank=True)
   date_of_birth = models.TimeField()

   def __str__(self):
       return self.author.username + ("'s profile")

# views.py
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy


class SignUpView(CreateView):
   form_class = CustomUserCreationForm
   template_name = "registration/signup.html"
   success_url = reverse_lazy("profile_create")

# project-level urls.py
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from django.views.generic.base import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path("accounts/", include("accounts.urls")),
    path("accounts/", include("django.contrib.auth.urls")),
    path("profile/", include("userprofiles.urls")),
    path("", TemplateView.as_view(template_name="home.html"), name="home"),
   ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# app-level urls.py
from django.urls import path
from .views import ProfileCreateView

urlpatterns = [
     path("create/", ProfileCreateView.as_view(), name="profile_create")
 ]


# profile_create.html
 {% extends 'base.html' %}

 {% block title %}Create Your Profile{% endblock title %}

 {% block content %}

 <h2>Create Your Profile</h2>
 <form method="post">
    {% csrf_token %}
    {{ form.as_p }}

    <button type="submit">Create my profile</button>
 </form>

{% endblock content %}

告诉我它有什么问题,我被卡住了,谢谢

我相信你错过了 enctype 的 html 形式,

enctype="multipart/form-data"

来自 docs

Note that request.FILES will only contain data if the request method was POST, at least one file field was actually posted, and the that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

HTML表格应该是,

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}

    <button type="submit">Create my profile</button>
 </form>