Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB
MU
Feb. 4, 2019, 5:46 p.m.

Django getstream integration problem

Django, django, python, python3

Hi, maybe this community help me.

I try integrate Getstream.io on my project. Following this code: https://github.com/GetStream/django_twitter I create most things like activity feed and notification but i don't know how to create a form to follow other people on profile page. (userdetailpage)

Code say how to create follow button on user list page but no on detail page.

Code to follow other people on list user page:

# Views

class DiscoverView(TemplateView):
    template_name = 'stream_twitter/follow_form.html'

    def get_context_data(self):
        context = super(DiscoverView, self).get_context_data()

        users = User.objects.order_by('date_joined')[:50]
        following = []
        for i in users:
            if len(i.followers.filter(user=self.request.user.id)) == 0:
                following.append((i, False))
            else:
                following.append((i, True))

        context['users'] = users,
        context['form'] = FollowForm()
        context['login_user'] = self.request.user
        context['following'] = following

return context

class FollowView(CreateView):
    form_class = FollowForm
    model = Follow
    success_url = reverse_lazy('timeline_feed')

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(FollowView, self).form_valid(form)


class UnfollowView(DeleteView):
    model = Follow
    success_url = reverse_lazy('timeline_feed')

    def get_object(self):
        target_id = self.kwargs['target_id']
return self.get_queryset().get(target__id=target_id)

#Forms
class FollowForm(forms.ModelForm):

    class Meta:
        exclude = set()
        model = Follow

#Urls

    path('follow/', login_required(views.FollowView.as_view()), name='follow'),
    re_path(r'^unfollow/(?P<target_id>\d+)/', login_required(views.UnfollowView.as_view()),
    name='unfollow'),

#Template

    {% for one, followed in following %}
    <div class="col-md-3 col-sm-6 col-xs-12">
      <div class="user">
      {% include "stream_twitter/_user.html" with user=one %}
      <div class="follow-button">
       <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" value="Create" />
        {% if followed %}
          Unfollow
        {% else %}
          Follow
        {% 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 %}
10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
2

Hello,

I think, will be better to use AJAX requests, without common form. For example, I have an article with my own system with Likes Dislikes.

In fact I have two sides fot implementing of these logic.

  1. It is button for executing ajax request.
  2. And I have VotesView for executing likes-dislikes logic.

Therefore, I think you can create url path with ID of user, which you want use for following logic.

path('follow/<int:target_user>/', login_required(views.FollowView.as_view()), name='follow'),

And implement FollowView

class FollowView(View):

    def get(self, request, target_user_id):
        authenticated_user = request.user # this is your authenticated user
        target_user = get_object_or_404(User, id=target_user_id) # your target user

        # ToDo implement your logic for following

        return HttpResponse()

And JavaScript logic for Ajax like in the article.

Sorry, I haven`t experiense with django_twitter library, but I think it will be first, what I will try.

0
MU

Thanks, i know Your Like Dislike system is cool. :D

0

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
April 26, 2019, 2:45 a.m.
djanaibekova_0301@mail.ru

C++ - Тест 003. Условия и циклы

  • Result:42points,
  • Rating points-8
Z
April 25, 2019, 8:02 p.m.
ZadvornyAlexey

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

  • Result:60points,
  • Rating points-1
m
April 24, 2019, 2:30 p.m.
maksImkа

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
April 21, 2019, 4:22 p.m.
Евгений Легоцкой

Через метод setIcon table.horizontalHeaderItem(0).setIcon("qrc://path/to/icon.png")
April 21, 2019, 3:48 p.m.
Евгений Легоцкой

Добрый день! Спасибо за комментарий. Там действительно лучше будет сделать с инициализацией по умолчанию.
U
April 18, 2019, 3:37 p.m.
Unreal_man

А как иконку в хедер задать?
u
April 18, 2019, 2:15 a.m.
uaa

доброго времени,большое спасибо за пример для начинающего)при адаптации к своему проекту столкнулся с таким ньансом:в vepolyline.h в 47 строке нужна инициализация по умолчанию: int m_pointF...
E
April 11, 2019, 12:49 p.m.
Evgeny

Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл Q_OBJECT в начале класса указать.
Now discuss on the forum
April 25, 2019, 10:51 a.m.
Ruslan Polupan

Изменил функциютеперь работает. bool ModelTerminals::setData(const QModelIndex &index, const QVariant &value, int role){ Q_UNUSED(role) if(!index.isValid()) {return false;...
April 24, 2019, 6:20 a.m.
Ruslan Polupan

я так понимаю надо инфорация об устройствах.Я бы пробовал так rust@suse:~> lsblk -PNAME="sda" MAJ:MIN="8:0" RM="0" SIZE="111,8G" RO="0" TYPE="disk" MOUNTPOINT=""NAME="sda1" MAJ:MIN="8...
April 21, 2019, 4:16 p.m.
Евгений Легоцкой

Приветствую Нужно сохранять где-то выбранное значение, а потом восстанавливать его. Или использовать QSettings или добавить метод open(), в который передавать начальные значения для того...
R
April 19, 2019, 9:55 a.m.
RED_Spider

мені важко це зараз навіть перевірити, тому що знайшов коміт, це ще було в 2016 році, і цей код не буде працювати коректно зараз, єдине скажу що це були QThread
Join us in social networks

For registered users on the site there is a minimum amount of advertising