Система запросов друзей Django
Я пытаюсь сделать систему запросов друзей на Django для приложения для кошек, и у меня возникла проблема. У меня есть модели для отслеживания друзей и запросов друзей. В представлениях у меня есть представление перенаправления с пунктом try except, который создает новый экземпляр модели запроса друга. Затем запрос друга будет показан тому, кому он был отправлен, и он примет или отклонит его. Проблема в том, что я не знаю, как получить информацию о пользователе, которому отправлен запрос на дружбу. Любая помощь будет принята с благодарностью. Вот ссылка на репозиторий моего проекта https://github.com/codewiz9/chatter
modles.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'
Вот как я бы реализовал такую модель:
class FriendRequest(models.Model):
# create a tuple to manage different options for your request status
STATUS_CHOICES = (
(1, 'Pending'),
(2, 'Accepted'),
(3, 'Rejected'),
)
# store this as an integer, Django handles the verbose choice options
status = models.IntegerField(choices=STATUS_CHOICES, default=1)
# store the user that has sent the request
sent_from = models.ForeignKey(User, ..., related_name="requests_sent")
# store the user that has received the request
sent_to = models.ForeignKey(User, ..., related_name="requests_received")
sent_on = models.DateTimeField(... # when it was sent, etc.
Теперь вы заметите, что два пользовательских поля ForeignKey имеют атрибуты related_name
, это обратные аксессоры, с помощью которых вы можете получить связанные объекты модели.
Допустим, у вас есть заданный объект user
, вы можете получить все запросы друзей, которые они отправили и получили, используя следующие запросы:
# Friend requests sent
user.requests_sent.all()
# Friend requests received from other users
user.requests_received.all()
Они предоставляют вам наборы запросов других пользователей, которые вы можете затем итерировать и получать к ним доступ по мере необходимости.