MU
Nov. 2, 2019, 3:22 p.m.

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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
4

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

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()

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

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
June 6, 2020, 12:20 a.m.
Aleksej

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
June 6, 2020, 12:15 a.m.
Aleksej

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
V
June 5, 2020, 5:47 p.m.
Vladzo

C++ - Test 005. Structures and Classes

  • Result:83points,
  • Rating points4
Last comments
June 5, 2020, 11:52 a.m.
progammist

Распознавание изображений на Python с помощью TensorFlow и Keras

Огромное спасибо за метериал, по-больше бы подобных статей (с подробным описанием работы и примерами применения) на тему современных технологий. Вопрос поразмышлять. На текущий момент реал…
June 5, 2020, 2:39 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

По-моему, смысла в этом нет особого. Если делегат будет игнорировать настройки таблицы, то это приведёт ещё к большему непониманию, что вообще происходит, для программиста, который после вас буд…
June 5, 2020, 2:34 a.m.
IscanderChe

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Сижу, размышляю: можно ли переписать делегата так, чтобы независимо от настроек строк выделялись строки?
June 5, 2020, 2:31 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Понятно. Я не обратил внимания на то, что там было в старом коде по настройкам строк :)
Now discuss on the forum
s
June 6, 2020, 2:54 a.m.
shuric

Qt/C++ Определение положения курсора над действие(кнопкой) в QToolBar

Доброго дня. Возник вопрос - как можно определить что курсор находится над определенным действием(кнопкой) в qtoolbar ? mainwindow.cpp MainWindow::MainWi…
s
June 6, 2020, 1:45 a.m.
shuric

Qt/C++ особенности QProxyStyle

Да, Вы правы. Код был скопирован с сайта (уже не помню с какого), но решил пойти по пути более легком. Пришлось переписать - кому интересно: использовал stackedWidget для пе…
June 6, 2020, 12:08 a.m.
Aleksej

Посоветуйте новичку (базы данных и Qt, что учить)

Блин, а я недавно купил Шлее Qt 5.10 :( С детства хотел стать программистом, баловался Паскалем, писал простенькие программки на Delphi, создавал движок на php, изучал C (забросил и перешел на п…
June 5, 2020, 2:09 p.m.
IscanderChe

QPlainTextEdit настройка цвета фона

Вечер добрый. Пытаюсь настроить цвет фона QPlainTextEdit следующим образом: CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent){ ... QPalette::ColorRole role = bac…
June 5, 2020, 7:13 a.m.
IscanderChe

Фильтр для QtableView sql

Добрый день. Для такой фильтрации необходимо использовать QSortFilterProxyModel. В оффдоках есть хороший пример.
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB