未保存django imagefield

s8vozzvw  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(356)

虽然我在表单中选择了图像,但图像更改不会保存。其他输入正在保存。请帮帮我。
html格式:

<form method="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    {{settingform}}
<button type="submit">Save</button>
</form>

型号.py:

from django.db import models

class SiteSetting(models.Model):
    logo = models.ImageField(blank=True, verbose_name="Logo")

    @property
    def logo_url(self):
        if self.logo and hasattr(self.logo, 'url'):
            return self.logo.url

视图.py:

def SiteSettingsView(request):
    settings = SiteSetting.objects.all()
    settingform = SiteSettingForm(instance=settings[0])
    if request.method == 'POST':
        settingform = SiteSettingForm(request.POST, instance=settings[0])
        if settingform.is_valid():
            settingform.save()
            return redirect('home')
    context = {
        'settings': settings[0],
        'settingform': settingform
    }
    return render(request, 'x.html', context)

表单.py:

from site_setting.models import SiteSetting

class SiteSettingForm(forms.ModelForm):
    class Meta:
        model = SiteSetting
        fields = '__all__'
tuwxkamq

tuwxkamq1#

你还必须提供 request.FILESSiteSettingForm :

settingform = SiteSettingForm(request.POST, request.FILES, instance=settings[0])

见基本文件上传(django文档)

相关问题