'How to put data in the db when you press a button in django

<button  href="{% url 'one' one.id_n %}" class="bg-gray-900 shadow-lg rounded p-3 overflow-hidden hover:shadow-xl hover:scale-105 duration-500 transform transition cursor-pointer">
<div class="group relative">
<img class="w-full md:w-72 block rounded" src="{{ one.f1 }}" alt="" />
</div>
</button >

I'm begginer with django and i want to add data as "one.id_n" to the db when you press the buttpm.



Solution 1:[1]

You can do something like this :

Into urls.py:

urlpatterns = [
    path("one/<int:id_n>", views.get_one_view, name="one"),
    ...
]

Into models.py:

class MyOneModel(models.Model):
    one_id = models.IntField(default=-1)

Into views.py:

def get_one_view(request, id_n):
   
    MyOneModel.objects.create(one_id = id_n)        

    return render(request, "one.html", {})

Solution 2:[2]

Django data submission is by http POST, which almost always corresponds to using a form and a view. Having POSTed, the view usually redirects to a new page. In other words, the "link" is the redirection in the view.

Sorry to say this, but you really need to work through one of the basic Django tutorials. I would advise skipping function-based views and learn to use Class-Based view FormView, but that's an opinion.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin13
Solution 2 nigel222