MU
3 ноября 2019 г. 1:22

Django follow unfollow

Django, django, python

Hi,

I try to solve my problem. I have follow and unfollow button on profile page, and on this page button works but I need to create this button on other pages. My problem is to filter when user is in target or not.

On profile page I have code:

  1. {% if profile_user.followed %}
  2. <a href="{% url 'unfollow' profile_user.id %}" class="btn btn-danger-gradiant btn-rounded letter-spacing-1" id="follow">Przestań obserwować</a>
  3. {% else %}
  4. <a href="{% url 'follow' profile_user.id %}" class="btn btn-danger-gradiant btn-rounded letter-spacing-1" id="follow">Obserwuj</a>
  5. {% endif %}
  6.  

In views this looks like that:

  1. def profile(request, username):
  2. '''
  3. Shows the users profile
  4. '''
  5. enricher = Enrich(request.user)
  6. profile_user = get_object_or_404(User, username=username)
  7. feed = feed_manager.get_user_feed(profile_user.id)
  8. activities = feed.get(limit=25)['results']
  9. context = {}
  10. do_i_follow_users(request.user, [profile_user])
  11. context['profile_user'] = profile_user
  12. context['activities'] = enricher.enrich_activities(activities)
  13. response = render(request, 'auth/user_detail.html', context)
  14. return response

This filter come from function "do_i_follow_users" as you can see in views. But how to take user in other situation like this:

  1. def goalcomments(request, slug):
  2. goal = get_object_or_404(Goal, slug=slug)
  3.  
  4. comments = goal.goalcomment.filter(active=True)
  5.  
  6. if request.method == 'POST':
  7. form = CommentGoal(data=request.POST)
  8. if form.is_valid():
  9. goal_comment = form.save(commit=False)
  10. goal_comment.author = request.user
  11. goal_comment.goal = goal
  12. goal_comment.save()
  13. else:
  14. form = CommentGoal()
  15. return render(request, 'goals/comments.html',
  16. {'goal': goal,
  17. 'comments': comments,
  18. 'form': form})

I don't know how to add this function "do_i_follow_users(request.user, [profile_user])" on view "commentgoal".
My Follow model is:

  1. class Follow(Activity, models.Model):
  2.  
  3. user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following_set')
  4. target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower_set')
  5. created_at = models.DateTimeField(auto_now_add=True)
  6. deleted_at = models.DateTimeField(blank=True, null=True)

I must check if comment author is in target. Maybe someone help me.

2

Вам это нравится? Поделитесь в социальных сетях!

4
Evgenii Legotckoi
  • 3 ноября 2019 г. 2:05
  • (ред.)

Hello,

Can you show source of do_i_follow_users function. I some misunderstand mechanism of this function. This function only check following relation, or create following relations ?

And I want suggest you to usi django-friendship battery. It is ready django-app for follow/unfollow relations, and for friendship relations.

    MU
    • 3 ноября 2019 г. 3:18

    Ok :)

    This is this function:

    1. def do_i_follow_users(user, users):
    2. followed_user_ids = Follow.objects.filter(user_id=user.id, target__in=users, deleted_at__isnull=True).values_list('target_id', flat=True)
    3. for u in users:
    4. u.followed = u.id in followed_user_ids
    5.  
    6.  
    7. def do_i_follow(user, follows):
    8. do_i_follow_users(user, [f.target for f in follows])

    I use django getstream.io to create feed etc. I send signal after user click follow or unfollow to getstream. My follow and unfollow views:

    1. @login_required
    2. def follow(request, id):
    3.  
    4. user = get_object_or_404(User, id=id)
    5.  
    6. follow, created = Follow.objects.get_or_create(user=request.user,target=user)
    7.  
    8. return HttpResponse()
    9.  
    10. @login_required
    11. def unfollow(request, id):
    12.  
    13. user = get_object_or_404(User, id=id)
    14.  
    15. follow, created = Follow.objects.get_or_create(user=request.user,target=user)
    16. follow.delete()
    17.  
    18. return HttpResponse()
      Evgenii Legotckoi
      • 3 ноября 2019 г. 15:37

      If you want check, is request.user in following users, then I think you can use custom template filter tag.

      For example I have user_in filter

      1. @register.filter
      2. def user_in(objects, user):
      3. if user.is_authenticated:
      4. return objects.filter(user=user).exists()
      5. return False

      using

      1. {% if objects|user_in:request.user %}
      2. {% elif %}
      3. {% endif %}

      I think you can create something else like this

      1. @register.filter
      2. def user_in(objects, user):
      3. if user.is_authenticated:
      4. users = [o.author for o in objects]
      5. return Follow.objects.filter(user_id=user.id, target__in=users, deleted_at__isnull=True).exists()
      6. return False

      and use it

      1. {% if goal_comments|user_in:request.user %}
      2. {% elif %}
      3. {% endif %}
        MU
        • 3 ноября 2019 г. 16:18
        • Ответ был помечен как решение.

        Thank you! For me work that:

        1. {% if comment.author.follower_set.all|user_in:request.user %}
        2. <a href="{% url 'unfollow' comment.author.id %}" class="btn btn-danger-gradiant btn-rounded btn-sm letter-spacing-1" id="follow">Przestań obserwować</a>
        3. {% else %}
        4. <a href="{% url 'follow' comment.author.id %}" class="btn btn-danger-gradiant btn-rounded btn-sm letter-spacing-1" id="follow">Obserwuj</a>
        5. {% endif %}

        and this templatetag:

        1. @register.filter
        2. def user_in(objects, user):
        3. if user.is_authenticated:
        4. return objects.filter(user=user).exists()
        5. return False

          Комментарии

          Только авторизованные пользователи могут публиковать комментарии.
          Пожалуйста, авторизуйтесь или зарегистрируйтесь