我有一个表,我希望添加一个编辑按钮,以更新特定记录的视觉和数据库。
我有一个HTML。
{% for work_entry in work_entries %}
{% if work_entry.date == date.date %}
<form action="{% url 'work_entries:object_edit' work_entry.id %}" method="post">
{% csrf_token %}
<tr>
<td>
<button onclick="return confirm('Are you sure you want this edit?')">Edit
</button>
</td>
<td> <form action="{% url 'work_entries:object_delete' work_entry.id %}" method="post">
{% csrf_token %}
<button onclick="return confirm('Are you sure you want to delete this record?')">Delete
</button>
</form>
</td>
<td>{{ work_entry.id }}</td>
<td><input type="text" value="{{ work_entry.description }}" name="description"></td>
<td><input type="number" value="{{ work_entry.num_hours }}" name="hours"></td>
</tr>
</form>
{% endif %}
{% endfor %}
views.py
def object_edit(request, object_id):
record = get_object_or_404(WorkEntry, pk=object_id)
if request.method == "POST":
record.description = request.POST["description"]
record.num_hours = request.POST["hours"]
record.save()
return redirect("/employeePage")
return render(request, "employeePage.html")
和urls.py
app_name = "work_entries"
urlpatterns = [
path("", views.employee_view, name="employeePage"),
url(r"^delete/(?P<object_id>[0-9]+)/$", views.object_delete, name="object_delete"),
url(r"^edit/(?P<object_id>[0-9]+)/$", views.object_edit, name="object_edit"),
]
我使用了一个输入标签,因为我认为这将允许我改变数据并保存它。然而,这是给我 employeePageedit14'description'处的MultiValueDictKeyError。 错误。我不是太有经验的jquery,从研究中我看到,可以工作,但我似乎没有得到它的权利。有人可以帮助甚至建议我应该如何接近这将是有用的。
注:已经有一个按钮来删除记录,这工作,我试过类似的方法来编辑,但它不工作。
我完全鼓励你使用 由Django提供的表格,它会让你的生活更轻松。
而且我也完全鼓励你不要用表格来删除东西,应该是一个简单的链接,这样可以避免在表格中出现表格。我想你的问题就出在这里。在表格中设置一个表格,中间有一个按钮,使你的浏览器无法知道你要提交表格的哪些部分。
同样,你有两个按钮,但没有一个是提交类型的。
如果你不想使用Django的表单,可以用以下方法来解决
{% for work_entry in work_entries %}
{% if work_entry.date == date.date %}
<form action="{% url 'work_entries:object_edit' work_entry.id %}" method="post">
{% csrf_token %}
<tr>
<td>
<button>
<a href="{% url 'work_entries:object_delete' work_entry.id %}" onclick="return confirm('Are you sure you want this edit?')">Delete</a>
</button>
</td>
<td> <button type="submit" onclick="return confirm('Are you sure you want to update this record?')">
Update
</button>
</td>
<td>{{ work_entry.id }}</td>
<td><input type="text" value="{{ work_entry.description }}" name="description"></td>
<td><input type="number" value="{{ work_entry.num_hours }}" name="hours"></td>
</tr>
</form>
{% endif %}
{% endfor %}
这不是最美的方式,我试着保持你的建筑风格