Home > Blockchain >  Django get current Model ID
Django get current Model ID

Time:01-23

Good Day, I have a delete btn for each created Title. When you click on the delete button, the model will be delete with the url localhost:8000/delete/OBJECT_ID

models.py

class NewTitle(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        default=None,
        null=True,
        on_delete=models.CASCADE,
    )
    title = models.CharField(max_length=200)
    creator_adress = models.GenericIPAddressField(null=True)
    id = models.BigAutoField(primary_key=True)

    def __str__(self):
        return str(self.title)

views.py

def title_view(request):
    custom_title_id = random.randint(1111, 1111111111111)

    titles =  # What to here, maybe NewTitle.pk?

    if request.method == 'POST':
        form = NewTitleForm(request.POST, instance=NewTitle(user=request.user))
        if form.is_valid():
            obj = form.save(commit=False)
            obj.creator_adress = get_client_ip(request)

            obj.id = custom_title_id
            while NewTitle.objects.filter(id=obj.id).exists():
                obj.id = random.randint(111, 11111111111)

            obj.save()
            return redirect('/another')
    else:
        form = NewTitleForm()
    return render(request, 'test.html', {'form': form, 'titles': titles})


def title_delete(request, title_id):

    user_title = NewTitle.objects.filter(id=title_id,
                                         user=request.user)
    if user_title:
        user_title.delete()
    else:
        return redirect('https://example.com')
    return HttpResponseRedirect('/another')

test.html

 {% for i in request.user.newtitle_set.all %}
    <p> {% if i.user == request.user %} {{ i.title }} {% endif %} <form action="delete/ #THE CURRENT OBJECT ID" method="POST">{% csrf_token %}<button type="submit">Delete Title</button></form> </p>
    {% endfor %}

Every 'Title' is displayed in the template. Next to each title there is a Delete button that leads to delete/OBJECT_ID. How can I set the action="" to the correct delete URL. So that I get the current ID of the title (object).

The interesting part is in views.py the titles variable and in test.html the second form action=""

Thank you very much! :-)

CodePudding user response:

You can use url template filter, but first you need to give the url which leads to title_delete a name (for example "delete_title"). Then for the button you can write action={% url 'delete_title' i.id %} . It will automatically create the url which leads to title_delete view and will also put the id in the request path.

  •  Tags:  
  • Related