0

I try to add follow button in django with Getstream.io app.

Following the getstream tutorial, django twitter, I managed to create a list of users with a functioning follow button as well as active activity feed. But when i try add follow button on user profile page, form send POST but nothing happends later.

I spend lot of time trying resolve this, but i'm still begginer in Django.

Code:

Follow model:

class Follow(models.Model):
        user = models.ForeignKey('auth.User', related_name = 'follow',         on_delete = models.CASCADE)
        target = models.ForeignKey('auth.User', related_name ='followers', on_delete=models.CASCADE)
        created_at = models.DateTimeField(auto_now_add = True)

        class Meta:
            unique_together = ('user', 'target')

    def unfollow_feed(sender, instance, **kwargs):
        feed_manager.unfollow_user(instance.user_id, instance.target_id)

    def follow_feed(sender, instance, **kwargs):
        feed_manager.follow_user(instance.user_id, instance.target_id)

    signals.post_delete.connect(unfollow_feed, sender=Follow)
    signals.post_save.connect(follow_feed, sender=Follow)

Views:

def user(request, username):
    user = get_object_or_404(User, username=username)
    feeds = feed_manager.get_user_feed(user.id)
    activities = feeds.get()['results']
    activities = enricher.enrich_activities(activities)
    context = {   
        'user': user,
        'form': FollowForm(),
        'login_user': request.user,
        'activities': activities,
    }
    return render(request, 'profile/user.html', context)

def follow(request):
    form = FollowForm(request.POST)
    if form.is_valid():
        follow = form.instance
        follow.user = request.user
        follow.save()
    return redirect("/timeline/")

def unfollow(request, target_id):
    follow = Follow.objects.filter(user=request.user, target_id=target_id).first()
    if follow is not None:
        follow.delete()
    return redirect("/timeline/")

Forms:

class FollowForm(ModelForm):

    class Meta:
        exclude = set()
        model = Follow

Urls:

path('follow/', login_required(views.follow), name='follow'),
path('unfollow/<target_id>/', login_required(views.unfollow),  name='unfollow'),

And user.html

<form action="{% if request.user in User.followers.all %}{% url 'unfollow' target.id %}{% else %}{% url 'follow' %}{% endif %}" method="post">
        {% csrf_token %}
        <input type="hidden" id="id_target" name="target" value="{{target.id}}">
        <input type="hidden" id="id_user" name="user" value="{{user.id}}">
                              <button type="submit" class="btn btn-primary btn-sm" value="Create" />
        {% if request.user in User.followers.all %}
        Unfollow
        {% else %}
        Follow
        {% endif %}
        </button> 
</form>

This form work in list user page:

 {% for one, followed in following %}
  <div class="col-md-3 col-sm-6 col-xs-12">
      <div class="card">
        <div class="card-body">
      {% include "profile/_user.html" with user=one %}
       <form action="{% if followed %}{% url 'unfollow' one.id %}{% else %}{% url 'follow' %}{% endif %}" method="post">
        {% csrf_token %}
        <input type="hidden" id="id_target" name="target" value="{{one.id}}">
        <input type="hidden" id="id_user" name="user" value="{{user.id}}">
        <button type="submit" class="btn btn-primary btn-sm" value="Create" />
        {% if followed %}
          Przestań obserwować
        {% else %}
          Obserwuj
        {% endif %}
        </button> 
      </form>
      </div>
      </div>
    </div>
    {% if forloop.counter|divisibleby:'4' %}
    <div class="clearfix visible-sm-block visible-md-block visible-lg-block"></div>
    {% elif forloop.counter|divisibleby:'2' %}
    <div class="clearfix visible-sm-block"></div>
    {% endif %}
  {% endfor %}
  </div>

And user list Views.py

def discover(request):
    users = User.objects.order_by('date_joined')[:50]
    login_user = User.objects.get(username=request.user)
    following = []
    for i in users:
        if len(i.followers.filter(user=login_user.id)) == 0:
            following.append((i, False))
        else:
            following.append((i, True))
    login_user = User.objects.get(username=request.user)
    context = {
        'users': users,
        'form': FollowForm(),
        'login_user': request.user,
        'following': following
    }
return render(request, 'uzytkownicy.html', context)
  • Can you elaborate on "nothing happens"? Is there no Follow model created in your database, or is the model created but seemingly no relationship created at the Stream API? Perhaps instrument your `views.follow` and `views.unfollow` views to pinpoint where things are going wrong. And/or verify that `Follow.unfollow_feed` and `Follow.follow_feed` functions are being called. – Dwight Gunning Mar 05 '18 at 08:30
  • Hi, thanks for reply! I see, I forgot to add follow forms view to above code. Now they should be brighter. – zyjswiadomie Mar 05 '18 at 09:26
  • Answering other questions, when I click Follow on list user page, then i have ""POST /follow/ HTTP/1.1" 302 0", when i click unfollow: ""POST /unfollow/2/ HTTP/1.1" 302 0", but on Profile page, i see ""POST /follow/ HTTP/1.1" 302 0" but nothing change on getstream dashboard, and button not change to unfollow. – zyjswiadomie Mar 05 '18 at 10:12
  • It looks most likely the form isn't passing the `is_valid()` condition. Rather than always returning a redirect it would be more idomatic to handle errors by returning a 200 OK and a HTML document that describes that a problem occurred. – Dwight Gunning Mar 05 '18 at 10:43
  • I erase redirect, and check list users and profile follow button. In list i see in request information "target 2", user "1", but on profile page when i click follow, i see in request information, that target is empty, only mapping user id. – zyjswiadomie Mar 05 '18 at 10:55
  • Have you looked at the `form.errors` object? I'd suggest first taking a moment to review the docs on [Django Form processing](https://docs.djangoproject.com/en/2.0/topics/forms/#instantiating-processing-and-rendering-forms) and become familiar with Forms, Views and Models. I'd try simplifying and separating your follow and unfollow scenarios more distinctly so it's easier to debug and ask new SO questions about, if needed. – Dwight Gunning Mar 05 '18 at 11:31

0 Answers0