Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
March 10, 2019, 5:01 p.m.
Maciej Urmański

Hi, I try to show user object from category which they subscribe. But don't know exacly how.

I have four models: Board ( category ) Subject Embed and Subscribe (foreign to user and to board)

class Board(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    image = models.ImageField(upload_to='board-cover', verbose_name='Tło kategorii', null=True, blank=True)
    body = models.TextField(verbose_name='Opis kategorii')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

class Subscribe(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscribed_users')
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subscribed_boards')
    created_at = models.DateTimeField(auto_now_add=True)
    subscribe = models.BooleanField(default=False)

class Subject(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    body = models.TextField(blank=True, verbose_name='Treść')
    image = models.ImageField(upload_to='subject', null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subjects', verbose_name='Kategoria')
    votes = GenericRelation(LikeDislike, related_query_name='subjectsvotes')

class Embed(models.Model):
    url = models.URLField(max_length=255)
    title = models.CharField(max_length=255)
    description = models.TextField()
    thumbnail_url = models.URLField(max_length=255)
    html = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, blank=True, null=True, related_name='embeds')
    votes = GenericRelation(LikeDislike, related_query_name='embedvotes')

In my views I try something like this:

def feed(request):
    embeds = Embed.objects.filter(author=request.user)
    subscribed_ids = request.user.subscribed_users.values_list('id', flat=True)

    actions = embeds.filter(author_id__in=subscribed_ids)
    actions = actions[:10]

    return render(request, 'boards/feed.html',
                {'actions': actions})

but nothing show up.

March 7, 2019, 10:01 a.m.
Maciej Urmański


I try to save foreign key in django restframework serializer.

My goal is to save in database information from and this part works good. But I need to also save it in specific category. After add field "Board(my category name field)" I have error: null value in column "board_id" violates not-null constraint

Maybe here someone help me.

My model:

class Embed(models.Model):
    url = models.URLField(max_length=255)
    title = models.CharField(max_length=255)
    description = models.TextField()
    thumbnail_url = models.URLField(max_length=255)
    html = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria')


class SubmitEmbed(forms.Form):
    url = forms.URLField()
    board = forms.ModelChoiceField(queryset=Board.objects.all())


class EmbedSerializer(serializers.ModelSerializer):
    author = serializers.HiddenField(default=serializers.CurrentUserDefault())
    board = serializers.RelatedField(read_only=True)

    class Meta:
        model = Embed
        fields = '__all__'


def save_embed(request):

    if request.method == "POST":
        form = SubmitEmbed(request.POST)
        if form.is_valid():
            url = form.cleaned_data['url']
            r = requests.get('' + url + '&key=' + settings.IFRAMELY_KEY)
            json = r.json()
            serializer = EmbedSerializer(data=json, context={'request': request})
            if serializer.is_valid():
                embed =
                return render(request, 'embed/embeds.html', {'embed': embed})
        form = SubmitEmbed()

    return render(request, 'embed/embedadd.html', {'form': form})
Feb. 20, 2019, 2:11 p.m.
Maciej Urmański

Hi, i try to create list of users attendance in goal app.

But i don't know how to filter user.

I have Goal model:

class Goal(models.Model, Activity):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    image = ImageField(blank=True, verbose_name='Tło')
    body = HTMLField(verbose_name='Treść')
    tags = TaggableManager()
    created_at = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = AutoSlugField(populate_from='title')

and Joined model:

class Joined(models.Model, Activity):
    goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='joined')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='joined_users')
    created_at = models.DateTimeField(auto_now_add=True)
    joined = models.BooleanField(default=False)

I try:

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

    users = goal.joined_users.all()

    return render(request, 'goals/users.html',
                {'goal': goal,
                'users': users})

This makes error: 'Goal' object has no attribute 'joined_users'.

I try also:

users = User.objects.filter(joined_users__joined__in=goal)

but then error is: 'Goal' object is not iterable.

Feb. 4, 2019, 5:46 p.m.
Maciej Urmański

Hi, maybe this community help me.

I try integrate on my project. Following this code: 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( == 0:
                following.append((i, False))
                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)

class FollowForm(forms.ModelForm):

    class Meta:
        exclude = set()
        model = Follow


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


    {% 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' %}{% else %}{% url 'follow' %}{% endif %}" method="post">
        {% csrf_token %}
        <input type="hidden" id="id_target" name="target" value="{{}}">
        <input type="hidden" id="id_user" name="user" value="{{}}">
        <button type="submit" class="btn btn-primary" value="Create" />
        {% if followed %}
        {% else %}
        {% endif %}
    {% 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 %}
Jan. 25, 2019, 8:28 a.m.


Django, python, formsets

Django Formsets управляет сложными повторяющимися полями форм в представлении. Используя формуляры, вы можете узнать, сколько форм было изначально, какие были изменены, а какие должны быть удалены. Подобно формам и моделям форм, Django предлагает наборы моделей форм, которые упрощают задачу создания набора форм для формы, обрабатывающей несколько экземпляров модели.

Jan. 6, 2019, 12:48 p.m.


Django, templatetags, python

I share my implementation of built-in tags to form breadcrumbs with support for markup, as well as support for bootstrap css.

Wrote these tags to speed up site development speed. Now the work moves much faster, because the code has become more compact, and correcting errors in the breadcrumbs markup has become much easier, since now you only need to correct the code in one place.

Sept. 26, 2018, 11:55 a.m.

Python 3

python, pool, пул, шаблоны проектирования

Example of the design pattern An object pool in the Python programming language.

Sept. 13, 2018, 12:03 p.m.

Python 3

abstract, factory, abc, python

An example of an abstract factory in the Python programming language

Jan. 15, 2017, 11:49 a.m.


PyQt5, QSettings, Qt, python

See Using QSettings in PyQt5. I propose to write a small application, which will be a single check box, the state of which we will save in the settings. Status checkbox will be saved by clicking on the checkbox. After closing the program and re-open this checkbox will be put to the state in which it was at the close of the program.

Nov. 18, 2016, 9:27 a.m.
Mirbadiev Shahboz

Всем привет, кто может подсказать, как проверить статус чекбокса, который находится в таблице QTableWidget.
Библиотека PyQt5
Заносил чекбокс в таблицу таким образом:

B=["ID отдела","Название","Артикул","Дата поступки","Срок хранения","Цена оптом","Цена розница","Кол-во",""]
self.tableWidget = QTableWidget(self.tab2)
cursor.execute("SELECT * FROM tovar")
rows = cursor.fetchall()
for row in rows:
self.tableWidget.setItem(countTID,0, QTableWidgetItem(str(row.id_otdela)))
self.tableWidget.setItem(countTID,1, QTableWidgetItem(str(row.nazvanie)))
self.tableWidget.setItem(countTID,2, QTableWidgetItem(str(row.artikul)))
self.tableWidget.setItem(countTID,3, QTableWidgetItem(str(row.data_postupki)))
self.tableWidget.setItem(countTID,4, QTableWidgetItem(str(row.srok_kh)))
self.tableWidget.setItem(countTID,5, QTableWidgetItem(str(row.cena_optom)))
self.tableWidget.setItem(countTID,6, QTableWidgetItem(str(row.cena_roznica)))
self.tableWidget.setItem(countTID,7, QTableWidgetItem(str(row.kolichestvo)))


Last comments
March 19, 2019, 12:57 p.m.

Добрый день. А проверить работоспособность локально как-то можно не указывая реальнй сайт (еще в разработке)
March 16, 2019, 1:55 p.m.

Спасибо за статью. Давно итересует следующий вопрос: с помощью переменных QMAKE_TARGET_COMPANYQMAKE_TARGET_PRODUCTQMAKE_TARGET_DESCRIPTIONможно задать свойства компилируемой программы, о...
March 12, 2019, 10:19 a.m.
Jean Stefanovich

Большое спасибо за разъяснения!
March 12, 2019, 10:04 a.m.
Евгений Легоцкой

Hello, In fact, this functionality or is not implemented, or is not documented. I'm not sure. But I think, that it should be implemented in Text QML Type. Because of we can write text in...
March 12, 2019, 9:51 a.m.
Евгений Легоцкой

Да вы правы. На самом деле проще через QSqlQueryModel, сколько не пытался использовать эти дженерики типо QSqlTableModel и QSqlRelationalTableModel, то всегда упирался в какие-то их ограничени...
Now discuss on the forum
March 19, 2019, 1:43 p.m.

Очень интересная тема. У вас случайно нет статьи с полным циклом интреграции нескольких языков?Так сказать с нуля, что нужно, какие пакеты ставить, что куда писать. Тут вроде информации не ма...
March 17, 2019, 10:47 p.m.
Евгений Легоцкой

Добрый день. Вот, нашлось у меня немного времени. Делается это через шаблон проектирования наблюдатель.
March 15, 2019, 9:52 p.m.
Чарльз Грин

спасибо, попробую, отпишусь
March 15, 2019, 7:41 p.m.

Сори догадался)
March 12, 2019, 4:57 p.m.

Большооооое спасибо!!!!!Не передать как я вам благодарен, спасибо что всегда отзываетесь.Теперь я смогу продолжить работу в QT!!! (пробую писать бота (Я как вы могли догадаться немного не пр...
Join us in social networks

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