我正在为我的项目构建一个好友请求系统。为此,我实现了以下功能,其中一个用户可以向另一个用户发送请求。
如果用户不是朋友(“朋友”对象中不存在关系),则显示“添加朋友”选项。
如果用户是朋友,然后以“ from_user”身份登录,则“ to_user”配置文件页面现在显示REQUEST SENT。
此后出现我的查询,当我从“ to_user”帐户登录并打开“ from_user”配置文件时,该按钮应为ACCEPT!不能弄清楚那是不是!在我的设置中,它显示添加朋友。因此需要帮助。
Models.py
class Friend(models.Model):
from_user = models.ForeignKey(User, on_delete=models.CASCADE )
to_user = models.ForeignKey(User, on_delete=models.CASCADE,
related_name="added" )
Views.py
class ProfilePage(DetailView):
model = models.UserCreation
context_object_name = 'profile'
def get_context_data(self, *args, **kwargs):
context = super(ProfilePage, self).get_context_data(*args, **kwargs)
user = User.objects.get(username=UserCreation.objects.get(id=self.kwargs.get('pk')))
print(user)
print(self.request.user)
try:
context['data'] = ProfileData.objects.get( user=user)
context['userdata'] = User.objects.get( username=user)
context['creationdata'] = UserCreation.objects.get( user=user)
context['sorted'] = sorted(chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)),key=lambda instance: instance.date, reverse=True)
context['friend'] = Friend.objects.get(from_user=self.request.user , to_user = user)
except ProfileData.DoesNotExist:
context['data']= None
except Friend.DoesNotExist:
context['friend']= None
return context
模板
{% if user.get_username|stringformat:'s' != creationdata.user|stringformat:'s' and creationdata.user|stringformat:'s' != friend.to_user|stringformat:'s' %}
<a href="{% url 'usercreation:addfriend' data.user.usercreation.pk %}" class="btn btn-primary" style="float:right">Add friend</a>
{% elif user.get_username|stringformat:'s' == friend.from_user|stringformat:'s' %}
<a href="#" class="btn btn-primary disabled" style="float:right">Request sent</a>
{% endif %}
答案 0 :(得分:0)
{% if friend %}
{% if friend.from_user_id == user.id %}
<a href="#" class="btn btn-primary disabled" style="float:right">Request sent</a>
{% endif %}
{% else %}
<a href="{% url 'usercreation:addfriend' data.user.usercreation.pk %}" class="btn btn-primary" style="float:right">Add friend</a>
{% endif %}