首页 > 解决方案 > Do actions on database object in Django Template

问题描述

Sorry for newbie question, but i'm not very familiar yet with Django.

What will be the best solution for this situation?

Let's say i have model class like this:

class ExampleItem(models.Model)
    name = models.TextField()
    ...
    #etc...

and a profile model which is linked to Auth.User

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    example_items = models.ManyToManyField(ExampleItem, related_name="items")

I have a example_item_details View, which passes ExampleItem data to template.

def example_item_details(request, id):
    example_item = get_object_or_404(ExampleItem, id=id)
    return render(request,
        'website/example_item_details.html',
        {'example_item': example_item})

in template i have a code which checks if example_item is added to manytomanyfield of profile example_items field.

In my template i have this code:

{% if request.user|check_if_item_is_user:example_item %}
<div class="button">
  Already Added
</div>
{% else %}
<div class="button">
  Add Item to your account
</div>
{% endif %}

I want to add "example_item" to "request.user.profile.example_items" on click on "Add Item to your account" or delete "example_item" from "request.user.profile.example_items" on click on "Already Item button" and reload page.

How can i do that without form?

标签: pythondjangotemplates

解决方案


推荐阅读