gpt4 book ai didi

django - 在django中上传图片时出错: "coercing to Unicode: need string or buffer, tuple found"

转载 作者:行者123 更新时间:2023-12-02 18:22:09 24 4
gpt4 key购买 nike

尝试在 django 中使用ImageField。这是我的模型

class Album(models.Model):
title = models.CharField(max_length=100)

def __unicode__(self):
return self.title

class Photo(models.Model):
image = models.ImageField(upload_to='photos/')
album = models.ForeignKey(Album)
title = models.CharField(max_length=100, default="")

def __unicode__(self):
return self.title

class PhotoModelForm(forms.ModelForm):
class Meta:
model = Photo

这是urls.py的一部分

...
url(r'^trial/upload/$', 'trial.views.upload'),
...

views.py

def upload(request):
if request.method == 'POST':
form = PhotoModelForm(request.POST, request.FILES)
if form.is_valid():
photo = form.save()
return render_to_response('trial/thanks_upload.html',{
'photo': photo
}, context_instance = RequestContext(request))
else:
form = PhotoModelForm()
return render_to_response('trial/upload.html', {
'form': form
}, context_instance = RequestContext(request))

上传.html

<form enctype="multipart/form-data" action="/trial/upload/" method="post">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Upload" /></p>
</form>

但是在保存时出现下一个错误:/试用/上传/处出现类型错误强制转换为 Unicode:需要字符串或缓冲区,找到元组

photo.save 上出现错误

有人知道为什么会这样吗?为什么会出现元组?我确信有一个愚蠢的错误......

最佳答案

我自己已经拿到了。在settings.py中有MEDIA_ROOT设置,即

MEDIA_ROOT = 'd:/dev/python/scripts/app/media/',

Python 由于末尾有逗号而将对象创建为元组。这就是它无法保存该对象的原因。下次注意你的逗号!

关于django - 在django中上传图片时出错: "coercing to Unicode: need string or buffer, tuple found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6185342/

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