gpt4 book ai didi

Django 图片上传表单无效

转载 作者:行者123 更新时间:2023-12-04 02:04:05 26 4
gpt4 key购买 nike

出于某种原因,在 django 中,我尝试使用的表单被认为是无效的。此代码几乎直接取自一个声称可以工作但仍无法正常工作的站点。我的代码如下。

观点

def display_update_image(request, pk):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
display = Display.objects.get(pk = pk)
display.image = form.cleaned_data['image']
display.save()
return HttpResponseRedirect(reverse('displays'))
else :
form = ImageForm()
return render(request, 'catalog/update_display_image.html', {'form': form})

TEMPLATE(模板名称为update_display_image.html)

<form method = "post" enctype = "multipart/form-data">{% csrf_token %}
<p>
<input id = "id" type = "file" class = "" name = "image">
</p>
<input type = "submit" value = "Submit" />

模型

class Display(models.Model):
title = models.CharField(max_length = 50,)
image = models.ImageField(upload_to = 'images')
id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True)

def __str__(self):
return self.title

编辑:忘记发布表单代码抱歉

class ImageForm(forms.Form):
image = forms.ImageField()

进一步编辑:将我的表单类更改为此

class ImageForm(forms.Form):
class Meta:
model = Display
fields = ('image',)

允许出于某种原因将表单读取为有效,但我不明白为什么。不幸的是,这导致我的视​​图方法无法正常运行,因为它无法再读取

display.image = form.cleaned_data['image']

最佳答案

如果您的表单类是模型表单:class ImageForm(forms.ModelForm): 您可以将实例传递给表单并保存它。

def display_update_image(request, pk):
if request.method == 'POST':
display = Display.objects.get(pk = pk)
form = ImageForm(request.POST, request.FILES, instance=display)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('displays'))
else :
form = ImageForm()
return render(request, 'catalog/update_display_image.html', {'form': form})

关于Django 图片上传表单无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44952529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com