我有一个视图和模板,可以创建搜索数据库中对象的查询。我还有一些列表,它们将根据不同的查询集创建用户名列表。 我传递了搜索到的查询集和两个待处理的列表和朋友。然后,我检查搜索查询中的用户名是否位于列表中。如果它们在列表中,它将根据它所在的列表显示不同的消息。如果它不在任何列表中,它将显示不同的消息。
错误+追踪:
AttributeError at /search/
'Friend' object has no attribute 'META'
Request Method: POST
Request URL: http://127.0.0.1:8000/search/
Django Version: 2.0.5
Exception Type: AttributeError
Exception Value:
'Friend' object has no attribute 'META'
Exception Location: /Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/template/context_processors.py in debug, line 40
Python Executable: /Users/omarjandali/anaconda3/envs/MySplit/bin/python
Python Version: 3.6.2
Python Path:
['/Users/omarjandali/Desktop/mysplit/mysplit',
'/Users/omarjandali/anaconda3/envs/MySplit/lib/python36.zip',
'/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6',
'/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/lib-dynload',
'/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages']
这是代码:
if request.method == "POST":
search = request.POST['search']
searched = User.objects.filter(username__contains = search).all()
searched |= User.objects.filter(first_name__contains = search).all()
searched |= User.objects.filter(last_name__contains = search).all()
requester = Friend.objects.filter(user = user).filter(requested = True).all()
requested = Friend.objects.filter(friend = user.username).filter(requested = True).all()
friended = Friend.objects.filter(user = user).filter(accepted = True).all()
friender = Friend.objects.filter(friend = user.username).filter(accepted = True).all()
pending = []
for request in requester:
pending.append(request.friend)
for request in requested:
pending.append(request.user.username)
print(pending)
friends = []
for friend in friended:
friends.append(friend.friend)
for friend in friender:
friends.append(friend.user.username)
print(friends)
parameters = {
'user':user,
'searched':searched,
'friends':friends,
'pending':pending,
}
return render(request, 'users/user_search.html', parameters)
这是tempalte:
{% for search in searched %}
{% if search.username != user.username %}
<p>
<a href="{% url 'view_profile' username=search.username %}">{{ search.username }}</a>
{% if search.username in pending %}
Pending
{% elif search.username in friends %}
Friends
{% else %}
<a href="{% url 'send_request' username=search.username %}">Send Request</a>
{% endif %}
</p>
{% endif %}
{% endfor %}
答案 0 :(得分:0)
构建pending
列表的for-in循环使用一个名为request
的变量来隐藏外部request
变量。当for-in循环结束时,request
的值是列表中的最后一个值(Friend
实例)。然后传递给render
,这将落空。
要解决此问题,请为循环变量使用与request
不同的名称 - 例如req
for req in requester:
pending.append(req.friend)
for req in requested:
pending.append(req.user.username)