MU
Maciej UrmańskiҚар. 2, 2019, 3: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:

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

In views this looks like that:

def profile(request, username):
    '''
    Shows the users profile
    '''
    enricher = Enrich(request.user)
    profile_user = get_object_or_404(User, username=username)
    feed = feed_manager.get_user_feed(profile_user.id)
    activities = feed.get(limit=25)['results']
    context = {}
    do_i_follow_users(request.user, [profile_user])
    context['profile_user'] = profile_user
    context['activities'] = enricher.enrich_activities(activities)
    response = render(request, 'auth/user_detail.html', context)
    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:

def goalcomments(request, slug):
    goal = get_object_or_404(Goal, slug=slug)

    comments = goal.goalcomment.filter(active=True)

    if request.method == 'POST':
        form = CommentGoal(data=request.POST)
        if form.is_valid():
            goal_comment = form.save(commit=False)
            goal_comment.author = request.user
            goal_comment.goal = goal
            goal_comment.save()
    else:
        form = CommentGoal()
    return render(request, 'goals/comments.html',
                {'goal': goal,
                'comments': comments,
                '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:

class Follow(Activity, models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following_set')
    target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower_set')
    created_at = models.DateTimeField(auto_now_add=True)
    deleted_at = models.DateTimeField(blank=True, null=True)

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

Рекомендуем хостинг TIMEWEB
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

4
Evgenii Legotckoi
  • Қар. 2, 2019, 4: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
    • Қар. 2, 2019, 5:18 Т.Қ.

    Ok :)

    This is this function:

    def do_i_follow_users(user, users):
        followed_user_ids = Follow.objects.filter(user_id=user.id, target__in=users, deleted_at__isnull=True).values_list('target_id', flat=True)
        for u in users:
            u.followed = u.id in followed_user_ids
    
    
    def do_i_follow(user, follows):
        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:

    @login_required
    def follow(request, id):
    
        user = get_object_or_404(User, id=id)
    
        follow, created = Follow.objects.get_or_create(user=request.user,target=user)
    
        return HttpResponse()
    
    @login_required
    def unfollow(request, id):
    
        user = get_object_or_404(User, id=id)
    
        follow, created = Follow.objects.get_or_create(user=request.user,target=user)
        follow.delete()
    
        return HttpResponse()
    
      Evgenii Legotckoi
      • Қар. 3, 2019, 4: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

      @register.filter
      def user_in(objects, user):
          if user.is_authenticated:
              return objects.filter(user=user).exists()
          return False
      

      using

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

      I think you can create something else like this

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

      and use it

      {% if goal_comments|user_in:request.user %}
      {% elif %}
      {% endif %}
      
        MU
        • Қар. 3, 2019, 5:18 Т.Ж.
        • Жауап шешім ретінде белгіленді.

        Thank you! For me work that:

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

        and this templatetag:

        @register.filter
        def user_in(objects, user):
            if user.is_authenticated:
                return objects.filter(user=user).exists()
            return False
        

          Пікірлер

          Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
          Кіріңіз немесе Тіркеліңіз
          OI
          • Ora Iro
          • Жел. 24, 2024, 6:38 Т.Ж.

          C++ - Тест 001. Первая программа и типы данных

          • Нәтиже:40ұпай,
          • Бағалау ұпайлары-8
          AD

          C++ - Тест 004. Указатели, Массивы и Циклы

          • Нәтиже:50ұпай,
          • Бағалау ұпайлары-4
          m
          • molni99
          • Қаз. 26, 2024, 1:37 Т.Ж.

          C++ - Тест 004. Указатели, Массивы и Циклы

          • Нәтиже:80ұпай,
          • Бағалау ұпайлары4
          Соңғы пікірлер
          ИМ
          Игорь МаксимовҚар. 22, 2024, 11:51 Т.Ж.
          Django - Оқулық 017. Теңшелген Django кіру беті Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
          Evgenii Legotckoi
          Evgenii LegotckoiҚаз. 31, 2024, 2:37 Т.Қ.
          Django - Сабақ 064. Python Markdown кеңейтімін қалай жазуға болады Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
          A
          ALO1ZEҚаз. 19, 2024, 8:19 Т.Ж.
          Qt Creator көмегімен fb3 файл оқу құралы Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
          ИМ
          Игорь МаксимовҚаз. 5, 2024, 7:51 Т.Ж.
          Django - Сабақ 064. Python Markdown кеңейтімін қалай жазуға болады Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
          d
          dblas5Шілде 5, 2024, 11:02 Т.Ж.
          QML - Сабақ 016. SQLite деректер қоры және онымен QML Qt-та жұмыс істеу Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
          Енді форумда талқылаңыз
          p
          pimacontrols85Жел. 31, 2024, 9:39 Т.Ж.
          Finding the Right Rittal Small Enclosure for Your Needs Rittal is a leading manufacturer of enclosures for industrial and IT applications. Their small enclosures offer a compact and reliable solution for a wide range of needs, from housing electronic…
          Donald Randolph
          Donald RandolphЖел. 30, 2024, 2:59 Т.Ж.
          Personal Injury lawyer Santa Monica As an experienced Santa Monica personal injury lawyer, Donald C. Randolph has recovered over $100 Million in verdicts and settlements for our clients. In severe injury cases, this compensation i…
          Nirvana Yoga School
          Nirvana Yoga SchoolЖел. 30, 2024, 5:13 Т.Ж.
          OAuth2.0 через VK, получение email Nirvana Yoga School is one of the most trusted and reputed traditional Rishikesh yoga courses , India certified by Yoga Alliance, USA. We aim to spread traditional yoga teachings so t…
          s
          sriparkЖел. 30, 2024, 4:47 Т.Ж.
          Mobile app development company in Chennai A Mobile app development company in Chennai focuses on creating personalized mobile applications to meet various business requirements. These companies offer a full range of services,…
          a
          amit88Жел. 30, 2024, 4:45 Т.Ж.
          Excel in Exams with PSLE Maths Tuition Singapore Preparing for the PSLE can be challenging, but the right guidance makes all the difference. PSLE Maths tuition Singapore offers personalized coaching to help students master key concepts, improv…

          Бізді әлеуметтік желілерде бақылаңыз