how to delete an object in django [duplicate] - python

i want to delete a task from the database so i use this code
this is my delete view
def task_Delete(request,id=None):
if request.method == 'POST':
form = TaskForm()
id = int(request.POST.get('task.id'))
task = Task.objects.get(id=id)
task.delete()
messages.success(request,"successfully delete")
return render_to_response('home.html', {'form': form})
and that is my urls.py
url(r'^task_Delete/$', views.task_Delete, name='task_Delete')
this the code of the button delete :
<form action="{% url 'task_Delete' %}" method="post" >
{% csrf_token %}
<input type="hidden" name="task_id" value="{{task.id}}" />
<input type="submit" value="delete task">
</form></td>
</tr>
when i click on delete nothing happend i don't know why , please help thanks in advance

There are various problems in your code (for example the TaskForm is not needed at all) however if you change the line
id = int(request.POST.get('task.id'))
to
id = int(request.POST.get('task_id'))
the object will probably be deleted; remember that the request parameter's name will be the same as the name of the input (task_id). I recommend using proper CBVs (a DeleteView) for what you want to do - if you want a slow and comprehensive tutorial on that I recommend this article: https://spapas.github.io/2018/03/19/comprehensive-django-cbv-guide/

Related

Reverse for 'customerdel' with arguments '('',)' not found.1 pattern(s) tried: ['dashboard/records/customerdel/(?P<pk>[0-9]+)$']

I am trying to delete an object from database using simple html button. Also, trying to implement "are you sure" message? BUt I am getting this error everytime and I am not able to crack.
This is my view function.
def customerdel(request,pk):
objs = Customer.objects.filter(id=pk)
if request.method == 'POST':
objs.delete()
# messages.success(request, 'Successfully deleted')
return render(request,'records.html')
else:
content ={
'items':Customer.objects.all
}
return render(request,'delete.html', content)
This is record.html page
<h1>Record's page</h1>
{% for abc in Customerdata %}
{{abc.name}}
{{abc.pk}}
<form >
<button class="btn btn-danger btn-sm">
Delete</button>
</form>
{% endfor %}
This is delete.html page
<h1>Welcome to Delete page</h1>
<p>Are you sure want to del {{items.name}} ??</p>
<form action="{% url 'customerdel' items.pk %}" method="post">
{% csrf_token %}
Cancel
<input name="confirm" type="submit" >
</form>
This is my URL.
path('dashboard/records/customerdel/<int:pk>', views.customerdel, name='customerdel'),
You are doing wrong while template rendering as you are not sending any data to the template.But inside the record.html you are trying to iterate over CustomerData which is not defined.So send it to the template or another way is to simply redirect to the route which is made for rendering record.html.
Here is the full code which you should apply in your django project to make it work.
from django.http import HttpresponseRedirect
from django.urls import reverse #these two lines are required for redirecting to a previous route(url)
As you must have set a url which takes to the records function something like this;
path('records', views.records, name='records')
If you haven't added the name, add it.
Then in views.py, in customerdel function;
if request.method == 'POST':
#write your code which you already wrote and instead of return render(...) write this;
return HttpResponseRedirect(reverse('records')) #where records is the name of the url which takes us to the records page.

How to loop through a form and add same form in django if we click add more button and store that in django

What I really want to do is , if a user click on "ADD more" button then a same form repeat itself and the values should store in database, if he/she doesn't click of that button then only the values from first form should be stored.
I am not able to get this, I just created a form , and a table in database for those details but can't loop though the form neither in data.
please help.
This is the form and the button:
This is the model.py code:
from django.db import models
class experience(models.Model):
company_name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
startdate = models.Datefield(default = 01-01-2020)
lastdate = models.DateField(default = 01-01-2020)
profile = models.CharField(max_length=100)
description = models.TextField(max_length = 250)
This is the views.py code:
from django.shortcuts import render, redirect
import requests
from django.contrib.auth.models import User, auth
# Create your views here.
def profile(request):
return render(request, 'profile.html')
Unfortunately, there's no built-in way (as far as I know) in Django to do that without Javascript, but here's an approach:
HTML:
<div class="container" id="experiencesContainer">
<form method='POST' name='experienceForm'>
{{form.as_p}}
</form>
<form method='POST' name='experienceForm'>
{{form.as_p}}
</form>
<button type="button" id="addMoreButton">Add more</button>
<button type="submit">Save Changes</button>
</div>
Django POST method:
# Get a list of submitted forms
experiences = request.POST.getlist('experienceForm')
for experience in experiences:
# this is how you loop throuh every form
experience.get('company_name)
Your javascript something like:
// clonning his childs as well
let cloneForm = document.querySelector('form[name=experienceForm]').cloneNode(true);
document.querySelector('div#experiencesContainer').appendChild(cloneForm);
// see this https://www.w3schools.com/jsref/met_node_clonenode.asp
Of course this code is not tested but I've done this in several projects before, hope it works!
A simple way would be to request the same view from the "Add", just make sure your form view saves the data when request method is POST.
<form action="{% url 'your-form-url' %}" method="GET">
{% csrf_token %}
<input type="submit" value="Add">
</form>
one other way to repeat forms would be using formsets. Formsets allow you to repeat the same form 'extra' times. Check out the documentation for more about this.
def repeat_form(request):
ExpFormSet = formset_factory(ExperienceForm, extra=3)
#extra defines the no. of forms you want to display
if request.method == 'POST':
formset = ExpFormSet(request.POST, request.FILES)
if formset.is_valid():
# do something with the formset.cleaned_data
#loop through each form in the formser
for form in formset.cleaned_data:
obj = form.save()
else:
formset = ExpFormSet()
return render(request, 'exp_form.html', {'formset': formset})
The corresponding template should be:-
<form method="post">
{{ formset.management_form }}
{% for form in formset %}
{{ form.as_p }}
{% endfor %}
</form>
Make sure you add form.management_form. Using the combination of the above might solve your problem of taking and saving several inputs.

How to access an attribute of a html tag in views with django

I have a html page which uses jinja to display a list.
I want to be able to get the user to click a button and the list will be added to a database. I have put the button in side a form and got it to link to my url which then calls a function.
HTML:
<form method='post' action='../../accounts/myaccount/' name= '{{item}}'>
{% csrf_token %}
<a name = '{{ item }}'><button type='submit' class='btn'><img src={% static 'results/images/basket_02.png' %} alt='Image cannot be displayed right now'></button></a>
</form>
Views:
def myaccount(request):
if request.user.is_authenticated():
if request.method == 'POST':
product = request.GET.get('name')
print('product: ' , product)
return render(request, 'signup/myaccount.html')
The function is called and it prints: product: NONE , whereas i want product to be set to the list.
I know how to add to database within my views but is there a way to actually access my list?
You need to use an input tag.
<input name="name" value="{{ item }}">

Django post request doing nothing

So i'm not even sure how to search for someone who had the same thing happen to them.
I'm working on a django website and my form won't post to my database, instead, i get redirected to a URL containing the information that was in the forms, like this:
<form id="form">
<input type="hidden" id="compinp" name="compinp">
<input maxlength="20" onkeyup="showpost()" name="title" id="titleinput">
{{ captcha }}
</form>
Where compinp is some other data that gets posted, {{ captcha }} is a reCaptcha checkbox that works just fine, and when everything is filled in and getting posted, instead of running the post function from views.py, instead i get redirected to this:
http://localhost:8000/newentry/?compinp=XXXX&title=XXXX&g-recaptcha-response="xxxx-xxxx-xxxx"
It gets posted via jQuery through a button outside of the form, though i tried to add a submit button inside it and got the exact same thing.
The views.py function that handles that looks like this:
def newentry(request):
if request.method == "GET" and request.user.is_authenticated():
#creating objects for the view, works fine too
return render(request, "newentry.html",
{"champlist": complist, "captcha": captcha})
elif request.method == "POST" and request.user.is_authenticated():
captcha = Captcha(request.POST)
title = request.POST.get("title", False)
compname = request.POST.get("compinp", False)
comp = Comp.objects.get(title=compname)
if captcha.is_valid() and title and compname:
newe= entry_generator(request.user, title, comp)
newe.save()
return redirect('/')
else:
return redirect('/')
else:
handle_home(request.method, request.user)
This view tries to post models from another app in the same project, if that makes it any different.
I had added a print attempt at the right after the request check for post it didn't print anything.
Not sure what other info i can give to help, if you want any, just ask (:
You need to add the form method post:
<form id="form" method="post">
<input type="hidden" id="compinp" name="compinp">
<input maxlength="20" onkeyup="showpost()" name="title" id="titleinput">
{{ captcha }}
</form>

Django python trying to use forms with token does not work for me

I'm learning django, in this moment I'm trying to implement web forms, actually some of them works fine with the data base model but I'm trying to make a new one without use the models. The problem is that django show me the token and not the value typed in the form.
I hope you can help me, to understand more about it.
URLS:
url(r'^test', views.test),
VIEWS:
def test(request):
if request.method == "POST":
return HttpResponse(request.POST)
return render(request, 'datos.html')
DATOS HTML:
<form action="/test" method="post" name="myForm"> {% csrf_token %}
<input type="text">
<input type="submit">
</form>
When I run this django show me:
csrfmiddlewaretoken
Can any one help me please?
To protect from Cross-Site_Request_Forgery attack, for each post request we need to send a csrf token, from the form, which is missing in your form, you can get rid of this error by modifying your form as follows.
<form action="/test" method="POST" name="myForm">
{% csrf_token %}
<input type="text">
<input type="submit">
</form>
and You need to get the data from your views,
def test(request):
if request.method == "POST":
# Getting the value of text field from the form
# If the value is empty set the default value to None
text = request.POST.get('text', None)
# Do not return the POST request
# Return the value you get from the form
return HttpResponse(text)
# This code is not going to execute
# Return is already encountered above in our code
return render(request, 'datos.html')
# To send data to form do,
# return render(request, 'datos.html', {'my_data': text})

Categories