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.

Do you like it? Share on social networks!

3
Evgenii Legotckoi
  • Feb. 14, 2019, 2:49 a.m.
  • The answer was marked as a solution.

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
    • Feb. 14, 2019, 5:56 a.m.
    • (edited)

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

      Evgenii Legotckoi
      • Feb. 14, 2019, 6 a.m.
      • (edited)

      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
        AD

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

        • Result:50points,
        • Rating points-4
        m

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

        • Result:80points,
        • Rating points4
        m

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

        • Result:20points,
        • Rating points-10
        Last comments
        i
        innorwallNov. 15, 2024, 2:30 p.m.
        Qt/C++ - Lesson 065. The correspondence of HTTP errors to server response errors in QNetworkAccessManager s Midsummer Classic in Kansas City priligy online pharmacy
        i
        innorwallNov. 15, 2024, 1:44 p.m.
        Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column? Many OPKs would advise users to start using the test strips around day 9 of your cycle, considering day 1 to be the first day of full menstrual flow buy priligy australia
        i
        innorwallNov. 15, 2024, 10:27 a.m.
        Release of C++/Qt and QML application deployment utility CQtDeployer v1.4.0 (Binary Box) optionally substituted alkoxy, optionally substituted alkenyloxy, optionally substituted alkynyloxy, optionally substituted aryloxy, OCH, OC H, OC H, OC H, OC H, OC H, OC H, O C CH, OCH CH OH, O…
        i
        innorwallNov. 15, 2024, 5:26 a.m.
        Qt/C++ - Lesson 031. QCustomPlot – The build of charts with time buy generic priligy We can just chat, and we will not lose too much time anyway
        i
        innorwallNov. 15, 2024, 3:03 a.m.
        Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime I didnt have an issue work colors priligy dapoxetine 60mg revia cost uk August 3, 2022 Reply
        Now discuss on the forum
        t
        tonypeachey1Nov. 15, 2024, 2:04 p.m.
        google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
        i
        innorwallNov. 15, 2024, 1:50 p.m.
        добавить qlineseries в функции priligy for sale Gently flush using an ear syringe
        i
        innorwallNov. 11, 2024, 6:55 p.m.
        Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
        9
        9AnonimOct. 25, 2024, 4:10 p.m.
        Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

        Follow us in social networks