Как убрать друга из множества полей? - PullRequest
0 голосов
/ 06 марта 2020

Я работаю на сайте знакомств, используя Django, где я могу добавлять и удалять друзей. У меня есть небольшие сложности с тем, как я могу удалить / удалить пользователя, которого я добавил. С кодом, который я попробовал, я получаю следующее сообщение об ошибке: «Не удается запросить« oghomwenoguns »: должен быть экземпляр« Профиль ».»

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
    bio = models.CharField(max_length=350, null=True,blank=True) 
    profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True)
    friends = models.ManyToManyField('Profile', blank=True)
    date = models.DateTimeField(auto_now_add=True, null= True)  

def delete_friend_request(request, id):
    my_friend = get_object_or_404(User,id=id)
    frequest = Profile.objects.filter(friends=my_friend)
    frequest.delete()
    return HttpResponseRedirect('/')

<a href="{% url 'site:delete_friend_request' u.id %}" class="btn btn-primary btn-lg waves-effect font-weight-bold text-capitalize ml-0 mt-2" style="font-size:14px;padding:10px;width:40%;">Unfriend</a>

1 Ответ

0 голосов
/ 06 марта 2020

В случае, если вы хотите удалить друга my_friend из request.user.friends.

Это будет примерно так:

def delete_friend_request(request, id):
    user_profile = request.user.profile
    friend_profile = get_object_or_404(Profile,id=id) # Profile instance has the same id as user
    user_profile.friends.remove(friend_profile) # A removes B
    friend_profile.friends.remove(user_profile) # B removes A
    return HttpResponseRedirect('/')

Вам просто нужно удалить его из friends список, не удаляйте пользовательский экземпляр.

Примечание: Убедитесь, что все User экземпляры имеют Profile.

Вы можете обновить текущие значения, используя эту последовательность команд:

python manage.py shell

from django.contrib.auth.models import User
from app_name.models import * # app_name must be the name of your application

user_with_no_profile = User.objects.filter(profile__isnull=True)

for u in user_with_no_profile:
  u.profile = Profile()
  u.save()

Видя ваш пример, обязательно раскрасьте html следующим образом, чтобы отображался только идентификатор друзей пользователя.

{% for u in request.user.friends.all %}
   <a href="{% url 'site:delete_friend_request' u.id %}" class="btn btn-primary btn-lg waves-effect font-weight-bold text-capitalize ml-0 mt-2" style="font-size:14px;padding:10px;width:40%;">Unfriend</a>
{% endfor %}

Отредактировано: Теперь оба друга удалены.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...