如何在 Django 上上传图片?

How do I upload images on django?

我一直在尝试使用自定义视图在 Django 中上传图像,但我失败了。管理面板让我上传,但可能是什么问题?我已经安装了 Pillow 并确保表单具有 multipart/form-data 属性。我应该为图像制作一个单独的模型吗?

models.py

class Profile(models.Model):
    username = models.OneToOneField(User, on_delete=models.CASCADE)
    gender = models.TextField(max_length=10)  
    dob = models.DateField(null=True, blank=True)  
    phone_no = models.CharField(unique=True, max_length=9)  
    address = models.CharField(max_length=50)  
    profile_pic = models.ImageField(null=True, blank=True, upload_to="profile_pic/")
    nrc_front = models.ImageField(null=True, blank=True, upload_to="nrc_front/")
    nrc_back = models.ImageField(null=True, blank=True, upload_to="nrc_back/")
    is_verified = models.BooleanField(default=False)
    is_group_admin = models.BooleanField(default=False)
    is_group_member = models.BooleanField(default=False)
    temp_code = models.CharField(max_length=6, null=True, blank=True)

    def __str__(self):
        return str(self.username)

settings.py

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(
    BASE_DIR / 'media'
)

view.py

def updateProfilePic(request):
    profiledata = get_profile_data(request)
    form = UpdateProfilePicForm()
    if request.method == "POST":
        form = UpdateProfilePicForm(request.POST, request.FILES)
        if form.is_valid():
            profile_pic = form.cleaned_data.get("profile_pic")
            Profile.objects.filter(username=request.user).update(profile_pic=profile_pic)
            return redirect('profile')
    else:
        form = UpdateProfilePicForm()
    context = {
        "profiledata":profiledata,
        "form":form
    }
    return render(request, 'base/profile-update-picture.html', context)

模板

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

{% block title %}Update Picture{% endblock %}

{% load crispy_forms_tags %}

{% block content %}
<div class="container">
    <div class="form-container shadow p-3 mb-5 bg-white rounded mx-auto">
        {% crispy form %}
    </div>
</div>
{% endblock %}

浏览器渲染

<form action="/update-profile-picture/" class="form-group" method="post" enctype="multipart/form-data">

在我的 url.py

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

您只需将此代码从 view.py

Profile.objects.filter(username=request.user).update(profile_pic=profile_pic)

收件人:

例如您的 table 用户是这样的:

class User(models.Model):
    name_user=models.CharField(max_lenght=50)

将 view.py 代码更改为:

Profile.objects.filter(username__name_user=request.user).update(profile_pic=profile_pic)

你能试试吗

Profile.objects.filter(username=request.user)

至:

user_profile = Profile.objects.get(username=request.user)
user_profile.profile_pic = profile_pic
user_profile.save()