You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django猫咪应用好友请求系统:无法获取请求接收方用户信息

Django猫咪应用好友请求系统问题解决

问题描述

我正在为一款猫咪应用开发基于Django的好友请求系统,已创建追踪好友关系和请求的模型,视图中写了带try-except的重定向视图来创建请求实例,请求会展示给接收方供其接受/拒绝,但不知道如何获取好友请求接收方的用户信息。

现有代码

models.py

from django.db import models
from django.utils.text import slugify
from django.contrib.auth import get_user_model
User = get_user_model()

# Create your models here.
class Chat(models.Model):
    messages = models.TextField(blank=True, max_length=2000, null=False),
    date = models.DateTimeField(blank=False, editable=False),
    slug = models.SlugField(allow_unicode=True, unique=True,),
    friends = models.ManyToManyField(User, through='Friend_List'),

class Friend_List(models.Model):
    friend_name = models.ForeignKey(User, related_name='name', on_delete=models.CASCADE),
    is_friend = models.BooleanField(default=False),

    def __str__(self):
        return self.user.username


class Friend_Info(models.Model):
    friend_name = models.ForeignKey(User, related_name='name', on_delete=models.CASCADE),
    slug = models.SlugField(allow_unicode=True, unique=True,),

class Friend_Request(models.Model):
    yes_or_no = models.BooleanField(default=False),
    friends = models.ManyToManyField(User, through='Friend_List'),
    slug = models.SlugField(allow_unicode=True, unique=True,),

views.py

from django.shortcuts import render
from django.urls import reverse
from django.views import generic
from .models import Chat, Friend_List, Friend_Info, Friend_Request
# Create your views here.

###Genral###
class Dashbord(generic.TemplateView):
    #This classs will have the list of all the users chats
    models = Chat, Friend_List
    template_name = 'chat_app/dashbord.html'


###Friends###
class Friend_Dashbord(generic.ListView):
    #This view will allow users to see thire friends and see thire friend requests and this will contain the button to add new friends
    models = Friend_Info, Friend_List
    template_name = 'chat_app/friend_dashbord.html'

class Friend_Request(generic.RedirectView):
    #This is the form for sending requests S=sent
    models = Friend_Request, Friend_list, Friend_Info
    def get(self, request, *args, **kwargs):
        friend = get_object_or_404(Friend_Info, slug=self.kwargs.get("slug"))

        try:
            Friend_Request.objects.create(friends=)

class Find_Friends(generic.FormView):
    #this will be the page where you can serch for friends
    models = Friend
    template_name = 'chat_app/dashbord.html'

###Chat###
#the chat portion of the app will be handeled in two parts one will the the form to send the chat and one will be the
#list of all the chats the form view will be inclued on the Chat_list template
class Chat_List(generic.ListView):
    #This will be the list of all the chats sent and resived
    models = Chat
    template_name = 'chat_app/dashbord.html'

class Chat_Form(generic.FormView):
    models = Chat
    template_name = 'chat_app/dashbord.html'

解决方案

1. 重构模型设计

现有模型关联逻辑混乱,重新设计核心模型以清晰区分好友请求和好友关系:

from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()

# 好友列表:每个用户对应唯一的好友列表,管理双向好友关系
class FriendList(models.Model):
    user = models.OneToOneField(User, related_name='friend_list', on_delete=models.CASCADE)
    friends = models.ManyToManyField(User, related_name='friends', blank=True)

    def add_friend(self, target_user):
        """双向添加好友"""
        if target_user not in self.friends.all():
            self.friends.add(target_user)
            self.save()
            target_user.friend_list.add_friend(self.user)

# 好友请求:直接关联发送方和接收方,记录请求状态
class FriendRequest(models.Model):
    sender = models.ForeignKey(User, related_name='sent_requests', on_delete=models.CASCADE)
    receiver = models.ForeignKey(User, related_name='received_requests', on_delete=models.CASCADE)
    is_accepted = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('sender', 'receiver')  # 避免重复发送请求

    def __str__(self):
        return f"{self.sender.username} -> {self.receiver.username}"

2. 修改视图获取接收方信息

发送好友请求视图(类视图)

from django.shortcuts import get_object_or_404
from django.views import generic
from django.urls import reverse
from .models import FriendRequest, User

class SendFriendRequest(generic.RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        # 通过slug获取接收方用户
        receiver = get_object_or_404(User, slug=self.kwargs.get('slug'))
        # 禁止给自己发请求
        if self.request.user != receiver:
            FriendRequest.objects.get_or_create(sender=self.request.user, receiver=receiver)
        return reverse('friend_dashboard')

好友面板视图(展示收到的请求)

class FriendDashboard(generic.ListView):
    template_name = 'chat_app/friend_dashboard.html'
    context_object_name = 'received_requests'

    def get_queryset(self):
        # 获取当前用户未处理的好友请求
        return FriendRequest.objects.filter(receiver=self.request.user, is_accepted=False)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 传递当前用户的好友列表
        context['friends'] = self.request.user.friend_list.friends.all()
        return context

3. 处理请求的视图(接受/拒绝)

from django.shortcuts import get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import FriendRequest

@login_required
def handle_friend_request(request, request_id, action):
    # 确保当前用户是请求接收方
    friend_request = get_object_or_404(FriendRequest, id=request_id, receiver=request.user)
    
    if action == 'accept':
        friend_request.is_accepted = True
        friend_request.save()
        # 双向添加好友
        request.user.friend_list.add_friend(friend_request.sender)
    elif action == 'reject':
        # 删除请求
        friend_request.delete()
    
    return redirect('friend_dashboard')

4. 路由配置示例

from django.urls import path
from . import views

urlpatterns = [
    path('friends/', views.FriendDashboard.as_view(), name='friend_dashboard'),
    path('friends/send/<slug:slug>/', views.SendFriendRequest.as_view(), name='send_friend_request'),
    path('friends/handle/<int:request_id>/<str:action>/', views.handle_friend_request, name='handle_friend_request'),
]

内容的提问来源于stack exchange,提问作者user17083547

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:39:21