'NoneType'对象没有属性'user'

时间:2013-05-18 13:56:09

标签: django django-models django-admin django-views

models.py

class Report(models.Model):
    user = models.ForeignKey(User, null=False)
    photo_files_attached = models.BooleanField('Photos', default=False)

views.py

def media(request):
    user = request.user  
    try:

        report = Report.objects.get(user=user.id)
    except:
        report = None

    report_dir = str(report.user.id) + '/' + str(report.id)
    output_dir = settings.MEDIA_ROOT + '/' + report_dir
    imagelist = []
    if os.path.exists(output_dir):
        os.chdir(output_dir)
        for files in os.listdir("."):
            for extension in JPEG_ALLOWED:
                if files.endswith(extension):
                    image_with_path = report_dir + '/' + files
                    imagelist.append(image_with_path)
    return render(request, 'incident/media.html',
                  {
                   'newreport_menu': True,
                   'report':report,

                 })   

我正在尝试上传图片文件并将其保存到数据库,收到以下错误“'NoneType' object has no attribute 'user'

2 个答案:

答案 0 :(得分:3)

似乎

Report.objects.get(user=user.id)

给你一个EmptyQuerySet

有问题的用户可能还没有任何关联的Report个实例。

您可以使用get_or_create

答案 1 :(得分:1)

您的代码中的报告似乎为None

try:
    report = Report.objects.get(user=user.id)
except:
    report = None # <---- your are most probably here

所以稍后report.user会提出'NoneType' object has no attribute 'user'。确保报告不是None并进行适当的检查。