'NoneType' object has no attribute 'user'

大城市里の小女人 提交于 2019-12-12 01:03:07

问题


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,

                 })   

I am trying to upload the image file and save it to database,getting the below error "'NoneType' object has no attribute 'user'"


回答1:


It seems

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

Gives you an EmptyQuerySet

The user in question probably hasn't got any associated Report instances yet.

You could use get_or_create




回答2:


It looks like report is None in your code:

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

So later report.user will raise 'NoneType' object has no attribute 'user'. Make sure report is not None and make appropriate checks.



来源:https://stackoverflow.com/questions/16625055/nonetype-object-has-no-attribute-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!