MU
Feb. 13, 2019, 5: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 %}
MU

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

ok. I see. You changed related name

Try this

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
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

DP
Oct. 19, 2019, 1:45 a.m.
Dmitrij Pasynkov

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

  • Result:26points,
  • Rating points-10
AS
Oct. 18, 2019, 1:27 p.m.
Artem Sergeevich

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

  • Result:13points,
  • Rating points-10
MB
Oct. 18, 2019, 11:05 a.m.
Mihail Bulatov

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

  • Result:86points,
  • Rating points6
Last comments
Oct. 17, 2019, 2:17 a.m.
Evgenij Legotskoj

Используем, там где требуется :)
MP
Oct. 17, 2019, 2:15 a.m.
Mikhail Petrov

Совет: подключайте ресурсы динамически. Используйте Resource Compiler: https://doc.qt.io/qt-5/rcc.html
Oct. 16, 2019, 6:45 a.m.
Evgenij Legotskoj

Если это не чистой воды спам, а по делу, то без проблем. Но в таком случае лучше создавайте отдельный вопрос на форуме . При создании вопроса есть поле, в котором можно указать статью…
KK
Oct. 16, 2019, 6:39 a.m.
Kirill Kirilych

А тут можно ссылки на сторонний ресурс показывать? Нашёл на habr похожую статью, только там чуток отличается код и про локальный сервер написано, нужно чтоб кто то понимающий посмотрел и своё …
Now discuss on the forum
Oct. 18, 2019, 1:30 p.m.
Evgenij Legotskoj

Добрый день. У вас там пробелы находятся в тексте, поэтому и не может сконвертировать. фукция map применяет float ко все символам в каждой строке. В том числе и к символам пробела. А пробе…
Oct. 17, 2019, 10:31 a.m.
Ruslan Volshebnik

Я вас понял) Спасибо ещё раз. Вы помогли мне во всём разобраться.
t
Oct. 17, 2019, 4:13 a.m.
tupo_chel

И тебе спасибо за помощь)
Oct. 17, 2019, 2:14 a.m.
Evgenij Legotskoj

Добрый день. Ну да, этот вариант жизнеспособен. Есть только один момент, который вам необходимо понимать в данном случае. И чего в этой статье или нет, или сказано как-то совсем вскользь, …
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB