我正在Django上构建CRUD应用程序。
我可以创建,读取和删除,但是更新功能不起作用。我已经编辑了views.py
文件(它是一个模板)以打印错误。
这是我的代码的相关部分:
#models.py
from django.db import models
class Item(models.Model):
id = models.AutoField(primary_key=True)
etype = models.CharField(max_length=100)
etitle = models.CharField(max_length=100)
eauthor = models.CharField(max_length=100)
estatus = models.CharField(max_length=20)
class Meta:
db_table = "Item"
#views.py
...
def edit(request, id):
item = Item.objects.get(id=id)
return render(request,'edit.html', {'item':item})
def update(request, id):
item = Item.objects.get(id=id)
form = ItemForm(request.POST, instance = item)
print(form.errors)
if form.is_valid():
try:
form.save()
except Exception as e: print(e)
return redirect("/items/show")
return render(request, 'edit.html', {'item': item})
...
我想这个问题必须记录edit.html
在案,但我无法弄清楚。
#edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}"/>
</head>
<body>
<form method="POST" class="post-form" action="http://127.0.0.1:8000/items/update/{{item.id}}">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type:</label>
<div class="col-sm-4">
<input type="text" name="etype" id="id_etype" required maxlength="100" value="{{ item.etype }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Title:</label>
<div class="col-sm-4">
<input type="text" name="etitle" id="id_etitle" required maxlength="100" value="{{ item.etitle }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Author:</label>
<div class="col-sm-4">
<input type="text" name="eatuhor" id="id_eauthor" required maxlength="100" value="{{ item.eauthor }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Status:</label>
<div class="col-sm-4">
<input type="text" name="estatus" id="id_estatus" required maxlength="20" value="{{ item.estatus }}" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</div>
</form>
</body>
</html>
PS:我对Django和软件开发都是陌生的,因此欢迎任何反馈。
我建议您使用UpdateView,它确实更容易。在这里显示请点击
示例views.py
class ItemUpdate(UpdateView):
model = Item
template_name = 'edit.html'
示例edit.html:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
</form>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句