MU
Maciej UrmańskiFeb. 13, 2019, 6: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
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
C

C++ - Test 005. Structures and Classes

  • Result:75points,
  • Rating points2
AE

C++ - Test 005. Structures and Classes

  • Result:25points,
  • Rating points-10
m

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

  • Result:28points,
  • Rating points-10
Last comments
AB

Qt/C++ - Lesson 008. QDataWidgetMapper - Working with the database via a widget

Понял сам так - происходит через setTable() "Sets the database table on which the model operates to tableName. Does not select data from the table, but fetches its field information", а затем че…
AB

Qt/C++ - Lesson 008. QDataWidgetMapper - Working with the database via a widget

Начал делать что-то похожее, но без sql. Не очень понимаю, что делает mapper->setCurrentModelIndex(model->index(row,0)); Вернее не понимаю вот что: откуда он берёт данные, кот…
IV

Qt/C++ - Lesson 048. QThread — How to work with threads using moveToThread

Не получается сделать connect, получаю гору ошибок. В чем может быть дело ?
IV

Qt/C++ - Lesson 034. Echo Server based on QTcpServer

Добрый день, разрешите вопрос: во всех примерах работы с QTcpServer его всегда создают в main.cpp, нет ли возможности корректно сохдать его в MainWindow.cpp ? Просто если перенести код…
D

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

А почему нельзя? Где можно об этом почитать? Киньте, пожалуйста, в меня ссылкой.
Now discuss on the forum

Отправка картинки в DRF

Да я знаю ;-) используйте, пожалуйста, в следующий раз средства сайта. В данном случае сторонний сервис ни к месту.
  • BlinCT
  • April 9, 2021, 8:15 a.m.

Работа с созданным обьектом qml через Qt.createComponent

Добрый день. И как это решает мою проблему?) Item{ id: root property var model property bool headers : false property string objectName property int iMaxWidthRow:…

Проект на cmake и QCharts

Кто-нибудь сталкивался с проблемой скроллинша чарта ? если допустим увеличить в ширину сам чарт, как скроолить весь чарт а не только его видимую часть ?

Ожидание ввода QLineEdit

Попробовал, крешится напрочь... Такое чуство что таймер не удаляется.... и к нему снова идет обращение....

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB