MU
Feb. 13, 2019, 11:30 p.m.

Django change button status

django, Django, Python

Hi,

I search through internet and review many apps but still don't have answer maybe on this forum someone help me.

I try to create changing button after user join to Goal.

I have work buttons, but i don't know how to change this in template.

I try to do this with boolean field, when user click "Join", boolean field change to True, and then in templates:

{% if goal.joined %}
<Delete join>
{% else %}
<join to goal>
{% endif %}

For now user can click many times on button and create many "join" objects in one goal. Now i know that i need to create variable in view that checks if the current user has joined the goal and add it to the context. But I don't know how. Im still newby.

class Goal(models.Model, Activity):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    image = models.ImageField(upload_to='goals', 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')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Cele'
        ordering = ['-created_at']

    def get_absolute_url(self):
        return reverse('goaldetail', args=[str(self.slug)])

    @property
    def activity_actor_attr(self):
        return self.author

    def add_user_to_list_of_attendees(self, user):
        registration = Joined.objects.create(user = user,
                                                    goal = self,
                                                    created_at = timezone.now())

    def remove_user_from_list_of_attendees(self, user):
        registration = Joined.objects.get(user = user, goal = self)
        registration.delete()

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)

    def save(self, *args, **kwargs):
        if self.id is None and self.created_at is None:
            self.created_at = datetime.datetime.now()
        self.joined = True
        super(Joined, self).save(*args, **kwargs)

    @property
    def activity_actor_attr(self):
        return self.user

Views:

def joined_add(request, pk):
    this_goal = Goal.objects.get(pk=pk)
    this_goal.add_user_to_list_of_attendees(user=request.user)
    return redirect('goaldetail', slug=this_goal.slug)

def joined_delete(request, pk):
    this_goal = Goal.objects.get(pk=pk)
    this_goal.remove_user_from_list_of_attendees(request.user)
    return redirect('goaldetail', slug=this_goal.slug)

def goaldetail(request, slug):
    goal = get_object_or_404(Goal, slug=slug)
    return render(request, 'goals/detail.html',
                {'goal': goal})

Path:

path('joined/<int:pk>', views.joined_add, name='joined_add'),
path('joined-delete/<int:pk>', views.joined_delete, name='joined_delete'),
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
3

Hello,

I think, You need to check user in joined_set in your case.

This is your custom template tag

from django import template

register = template.Library()


@register.filter
def user_in(objects, user):
    if user.is_authenticated:
        return objects.filter(user=user).exists()
    return False

The next step, check user in the set

{% load user_in from your_template_tags %}
{% if goal.joined_set.all|user_in:request.user %}
<Delete join>
{% else %}
<join to goal>
{% endif %}
0
MU

Edit: Works! Thank you very much! Just change goal.joined_set.all to goal.joined.all. :D

0

ok. I see. You changed related name

Try this

{% if goal.joined.all|user_in:request.user %}
1

Comments

Only authorized users can post comments.
Please, Log in or Sign up
m
May 19, 2019, 1:49 a.m.
mahhaki

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
S
May 17, 2019, 1:14 p.m.
SunBro

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
b
May 17, 2019, 4:18 a.m.
banana

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

  • Result:57points,
  • Rating points-2
Last comments
May 21, 2019, 8:10 p.m.
Дмитрий

Приветствую! Я думаю дойдёт и до этого, но пока изучать его у меня нет желания.
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
P.
May 18, 2019, 2:03 p.m.
PELMYACH .

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
P.
May 14, 2019, 10:33 p.m.
PELMYACH .

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
Now discuss on the forum
ДТ
May 22, 2019, 1:40 p.m.
Даниил Тетерин

Есть задание - сделать программу-расписание, где главное окно - календарь, в котором можно нажать на любой день, тогда откроется окно, в котором будут видны уже существующие на этот день зад...
В
May 22, 2019, 10:05 a.m.
Владислав

Данный код компилируется только для 32 битной системы, а на 64 битной выдаёт ошибку линковки LNK2019. Возможно ли как-то, используя функцию RegisterHotKey, использовать глобальные горячие клав...
I
May 22, 2019, 5:08 a.m.
Intruder

Евгений, доброго времени суток и спасибо! Все получилось.
May 20, 2019, 8:43 a.m.
Михаиллл

Кинул библиотеки в папку с проектом и в папку к компилируемым файлам.В файле проекта прописал так, но все равно выдает ту же ошибку QT += core gui networkgreaterThan(QT_MAJOR_VERSI...
May 20, 2019, 1:47 a.m.
linq

Что вы понимаете под статической сборкой приложений? В какой среде?

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

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