“我正在开发一个用于客户注册的 Django 项目,我遇到了‘删除’功能的问题。当我尝试删除客户信息时,它没有按预期工作。有人可以检查一下我的信息吗? ‘删除’功能并提出任何更正或改进吗?谢谢!”
这是我的 view.py 代码块。
from . models import Customer
from django.contrib import messages
def cutomer_registration (request):
message = ''
data = ''
number = 0
if 'ok' in request.POST:
name = request.POST['name'],
surname = request.POST['surname'],
email = request.POST['email'],
phone = request.POST['phone']
if name and surname and email and phone:
if Customer.objects.filter(email=request.POST['email']).exists():
message = "This email already exists."
elif Customer.objects.filter(phone=request.POST['phone']).exists():
message = "This phone already exists"
else:
save_data = Customer(
name = request.POST['name'],
surname = request.POST['surname'],
email = request.POST['email'],
phone = request.POST['phone '],
note = request.POST['note']
)
save_data.save()
message = "Customer registration was successful."
else:
message = "Fill in the appropriate boxes"
data = Customer.objects.all().order_by('-id')
number = Customer.objects.count
return render(request, 'registration_m.html', {'message' : message, 'data' : data, 'number' : number})
def del(request, id):
if 'delete' in request.POST:
customer = Customer.objects.get(id=id)
if 'yes' in request.POST:
customer.delete()
else:
return redirect('registration')
return render(request, 'registration_m.html', {'customer' : customer})
这是我的 html 代码块。
<h2>Customer Registration</h2>
<form method="post">
{% csrf_token %}
Name:<br>
<input type="text" name="ad"><br>
Surname:<br>
<input type="text" name="soyad"><br>
Phone:<br>
<input type="tel" name="telefon"><br>
E-mail:<br>
<input type="text" name="email"><br>
Note:<br>
<textarea cols="20" rows="5" name="note"></textarea><br><br>
<button name="ok">Qeyddiyyat</button>
</form>
{% if message %}
{{message}}
<br><br>
{% endif %}
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
<br><br>
{% endif %}
{% if number > 0 %}
There is <b>{{number}}</b> customer in base.<br><br>
{% endif %}
<form method="post">
{% csrf_token %}
{% for info in data %}
#{{forloop.counter}}<br>
<b>Customer:</b> {{info.name}} {{info.surname}}<br>
<b>Phone:</b> {{info.phone}}<br>
<b>E-mail:</b> {{info.email}}<br>
<a href="{% url 'delete' info.id %}"><button>delete</button></a>
{% if delete == info.id %}
<br><br>
Do you want to delete ID:{{info.id}}?
<br><br>
<button name="yes">Yes</button>
<button name="no">No</button>
<br><br>
{% endif %}
<br><br>
{% endfor %}
</form>
我尝试使用客户 ID 删除客户,然后在同一页面上询问是否删除该客户。
action="…"
[mdn] 属性中添加链接:
{% for info in data %}
<form method="post" action="{% url 'delete' info.id %}">
{% csrf_token %}
<b>Customer:</b> {{info.name}} {{info.surname}}<br>
<b>Phone:</b> {{info.phone}}<br>
<b>E-mail:</b> {{info.email}}<br>
<button type="submit">delete</button>
</form>
{% endfor %}