使用 Django ModelForm 上传个人资料图片

发布于 2024-12-02 14:14:53 字数 940 浏览 0 评论 0原文

我环顾过相关问题,但似乎没有一个答案有效。我正在尝试上传用户的个人资料图像并让它替换(覆盖)当前图像。保存图像后,我想将文件名更改为用户 ID。图像将以当前形式上传,但不会替换现有图像(例如,它将保存为 2_1.png)。

class PhotoForm(forms.ModelForm):
    def save(self):
        content_type = self.cleaned_data['photo'].content_type.split('/')[-1]
        filename = '%d.%s' % (self.instance.user.id, content_type)

        instance = super(PhotoForm, self).save(commit=False)
        instance.photo = SimpleUploadedFile(filename, self.cleaned_data['photo'].read(), content_type)
        instance.save()
        return instance

    class Meta:
        model = UserProfile
        fields = ('photo',)

def photo_form(request):
    if request.method == 'POST':
        form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
        if form.is_valid():
            form.save()
    else:
        form = PhotoForm()
    return render(request, 'photo_form.html', {'form': form})

I've looked around at related questions, but none of the answers seem to work. I'm trying to upload a profile image for a user and have it replace (overwrite) the current image. Upon saving the image I want to change the filename to the user id. In it's current form the image will upload, but it won't replace the existing image (e.g. it'll be saved as 2_1.png).

class PhotoForm(forms.ModelForm):
    def save(self):
        content_type = self.cleaned_data['photo'].content_type.split('/')[-1]
        filename = '%d.%s' % (self.instance.user.id, content_type)

        instance = super(PhotoForm, self).save(commit=False)
        instance.photo = SimpleUploadedFile(filename, self.cleaned_data['photo'].read(), content_type)
        instance.save()
        return instance

    class Meta:
        model = UserProfile
        fields = ('photo',)

def photo_form(request):
    if request.method == 'POST':
        form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
        if form.is_valid():
            form.save()
    else:
        form = PhotoForm()
    return render(request, 'photo_form.html', {'form': form})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昇り龍 2024-12-09 14:14:53
def photo_form(request):
    if request.method == 'POST':
        form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
        if form.is_valid():
            handle_uploaded_file(request.FILES['<name of the FileField in models.py>'])

def handle_uploaded_file(f):
    dest = open('/path/to/file', 'wb') # write should overwrite the file
    for chunk in f.chunks():
        dest.write(chunk)
    dest.close()

检查这里: https://docs.djangoproject.com/en/dev /主题/http/文件上传/
如果这不起作用,我想如果表单被接受,您可以使用 os.system 删除该文件。这可能不是一个很好的解决方案,但它应该有效。

def photo_form(request):
    if request.method == 'POST':
        form = PhotoForm(data=request.POST, file=request.FILES, instance=request.user.get_profile())
        if form.is_valid():
            handle_uploaded_file(request.FILES['<name of the FileField in models.py>'])

def handle_uploaded_file(f):
    dest = open('/path/to/file', 'wb') # write should overwrite the file
    for chunk in f.chunks():
        dest.write(chunk)
    dest.close()

check here: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/
If that doesn't work, I suppose you could just use os.system to delete the file if the form is accepted. That probably wouldn't be that great of a solution, but it should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文