0

我正在尝试创建一个简单的收件箱消息应用程序,但我一直遇到此错误。

我知道错误指向这里

if Message.objects.filter(in_response_to=messages.in_response_to):
     m = messages.in_response_to.id

我想要传达的是,如果它们是 messages.in_response_to 中的一个对象。做这个 。我不知道如何解决它,我花了几个小时尝试,有人可以帮助我吗

错误

'NoneType' object has no attribute 'id'
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "C:\mysite\pet\views.py" in read
  944.         m = messages.in_response_to.id

视图.py

@login_required
def read(request,id):
    try:
        messages = Message.objects.get(pk=id,recipient=request.user.id) 
    except Message.DoesNotExist:
        return HttpResponseRedirect(reverse('world:Display'))



    if Message.objects.filter(in_response_to=messages.in_response_to):
        m = messages.in_response_to.id
        message = Message.objects.filter(in_response_to=messages.in_response_to ).filter(created__lt=messages.created)

        initial = {}
        initial.update({'hidden_field': m})
        form = NewMessageForm(initial=initial)
        return render(request,'read.html',{'message':message,'form':form,'m':m})
    else:
        initial = {}
        initial.update({'hidden_field': messages.id})
        form = NewMessageForm(initial=initial)

        return render(request,'read.html',{'messages':messages,'form':form})

楷模。

class Message(models.Model):
    user = models.ForeignKey(User, related_name='sender')
    recipient = models.ForeignKey(User, related_name='recipient')
    created = models.DateTimeField(auto_now_add=True)
    in_response_to = models.ForeignKey('self', null=True, blank=True)


def __unicode__(self):
    return self.body

@Ignacio Vazquez-Abrams

    if Message.objects.filter(in_response_to=messages.in_response_to):
        m = messages.in_response_to.id
        message = Message.objects.filter(in_response_to=messages.in_response_to ).filter(created__lt=messages.created)

    initial = {}
    initial.update({'hidden_field': m})
    form = NewMessageForm(initial=initial)
    return render(request,'read.html',{'message':message,'form':form,'m':m})

initial = {}
initial.update({'hidden_field': messages.id})
form = NewMessageForm(initial=initial)

return render(request,'read.html',{'messages':messages,'form':form})
4

1 回答 1

2

你可以做:

if messages.in_response_to :
    m = messages.in_response_to.id
    ...
else:
    ...
于 2013-06-25T10:50:48.063 回答