尝试使用文件字段创建(&save)django 模型时出现以下错误:
/admin/app_name/template/add/ 处的类型错误
强制转换为 Unicode:需要字符串或缓冲区,找到 int
Request Method: POST
Request URL: http://localhost:8000/admin/app_name/template/add/
Django Version: 1.4.3
Exception Type: TypeError
Exception Value: coercing to Unicode: need string or buffer, int found
Exception Location: path_to_python\python\lib\site-packages\django\utils\encoding.py
in force_unicode, line 71
这是models.py:-
class Template(models.Model):
title = models.CharField(max_length=300, unique=True)
template = models.FileField(upload_to='templates')
def __unicode__(self):
return self.title
class TemplateAdmin(admin.ModelAdmin):
def upload_file(request,*args, **kwargs):
if request.method == 'POST':
instance = Template(template=request.FILES['template'])
instance.title =request.POST['title']
instance.save()
admin.site.register(Template, TemplateAdmin)
这是settings.py:-
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
此外,虽然在尝试保存(创建)模板对象时出现此错误,但文件似乎仍上传到指定目录中(因为我可以在该目录中找到它)......但是没有创建对象实例(如Template.objects.all()
返回一个空列表)。