MU
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.

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

Hi,

I try to save foreign key in django restframework serializer.

My goal is to save in database information from iframely.com 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')

Form:

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

Serializer:

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

    class Meta:
        model = Embed
        fields = '__all__'

View:

def save_embed(request):

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

    return render(request, 'embed/embedadd.html', {'form': form})
MU
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.

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

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 %}
Jan. 25, 2019, 8:28 a.m.

Django

Django, python, formsets

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

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

Django

Django, templatetags, python

I share my implementation of built-in tags to form breadcrumbs with support for schema.org 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

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.

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

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

B=["ID отдела","Название","Артикул","Дата поступки","Срок хранения","Цена оптом","Цена розница","Кол-во",""]
self.tableWidget = QTableWidget(self.tab2)
self.tableWidget.setRowCount(count1)
self.tableWidget.setColumnCount(9)
self.tableWidget.setColumnWidth(8,30)
self.tableWidget.setColumnWidth(0,120)
self.tableWidget.resize(920,400)
self.tableWidget.setHorizontalHeaderLabels(B)
cursor.execute("SELECT * FROM tovar")
rows = cursor.fetchall()
countTID=0
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)))
self.tableWidget.setCellWidget(countTID,8,QCheckBox())
countTID+=1
self.tableWidget.show()

 

N
June 25, 2019, 2:41 p.m.
Nico03

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

  • Result:40points,
  • Rating points-8
S
June 25, 2019, 9:16 a.m.
SabaNtuy

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

  • Result:40points,
  • Rating points-8
SZ
June 24, 2019, 5:49 p.m.
Serg Zhi

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

  • Result:78points,
  • Rating points2
Last comments
June 24, 2019, 10:23 a.m.
Евгений Легоцкой

Хорошо, ну будут проблемы помимо того, что касается статей, то не стесняйтесь задавать вопросы на форуме.
МБ
June 24, 2019, 10:21 a.m.
Михаил Булатов

Извиняюсь, все работает(из-за невнимательности).
June 24, 2019, 9:52 a.m.
Евгений Легоцкой

Придётся делать ещё сигнал в дочернем qml и пробрасывать через коннекты и обработчики. А вообще нужно смотреть конкретный код и что вы пытаетесь сделать. Так что лучше будет, если вы зад...
June 21, 2019, 8:31 a.m.
Ruslan Polupan

Вот моя строка по которой все отлично сработало %cqtdeployer% -bin c:/CentralMposKeys/CentalMposKeys.exe -qmake c:/Qt/5.12.2/mingw73_64/bin/qmake.exe
June 21, 2019, 8:24 a.m.
Андрей Янкович

Возможно кому то пригодится сqtdeployer для windows работает точно так же как и для Linux разница лишь в команде запуска Linux: cqtdeployer Windows: %cqtdeployer...
Now discuss on the forum
June 25, 2019, 6:16 p.m.
Алексей Внуков

только через webengine, прямого апи у Яндекса нет, вроде что-то есть у гугла, сам только начал интересоваться этим вопросом
June 25, 2019, 5:05 p.m.
Михаиллл

Само заработало. Странно.
June 25, 2019, 2:32 p.m.
Михаиллл

Похоже глюк вебсокета. К другим вебсокетам подключаюсь.
June 25, 2019, 1:55 p.m.
Андрей Янкович

падало потому что boolStatus был на стеке метода, после завершения метода переменная убивалась, и на обращении к ней было падение.просто сделай вот так: connect(&t, &QTimer::timeou...
June 25, 2019, 10:55 a.m.
IscanderChe

По пункту 3 попытался переписать метод setData. В итоге комбобокс перестал работать. bool MySqlTableModel::setData(const QModelIndex& index, const QVariant& value, int /* role */){...
Looking for a Job?
10,000.00 руб. - 15,000.00 руб.
Нужен помощник для создания API.
Moscow, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

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

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB