MU
Maciej UrmańskiАқп. 4, 2019, 12:46 Т.Қ.

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 %}
Рекомендуем хостинг TIMEWEB
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

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

2
Evgenii Legotckoi
  • Ақп. 4, 2019, 3:12 Т.Қ.

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.

    MU
    • Ақп. 13, 2019, 6:21 Т.Қ.

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

      Пікірлер

      Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
      Кіріңіз немесе Тіркеліңіз
      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 аналогично. Могу предположить, что из-за более новой верси…
      Енді форумда талқылаңыз
      n
      nklyҚаң. 3, 2025, 2:52 Т.Ж.
      Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
      AW
      Ayden WatkinsҚаң. 2, 2025, 12:09 Т.Ж.
      Why Paying for a Research Paper Can Be a Smart Choice Writing a research paper can be a daunting task, especially when faced with tight deadlines, complex topics, or a lack of resources. For many students, paying for a research paper is a practical…
      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…

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