在 Django 3.2 中處理一個簡單的專案并嘗試添加一個編輯按鈕來編輯頁面的內容。為此,我做了:views.py
def UpdateContent(request, pk):
contents = todo.objects.get(id=pk)
form = UpdateContent(instance=contents)
if request.method == 'POST':
form = UpdateContent(request.POST, instance=contents)
if form.is_valid():
form.save()
return redirect('/')
context = {'form': form}
return render(request, 'html/update.html', context)
表格.py
class UpdateContent(ModelForm):
class Meta:
model = todo
fields = ['content']
主頁.html
<table class="table table-dark table-hover table-bordered">
<thead>
<tr id="tr-table">
<th id="text-left">#</th>
<th id="text-center">ITEMS</th>
<th id="text-right"><i class="material-icons"></i></th>
</tr>
</thead>
<tbody>
{% for all_item in all_items%}
<tr>
<th id="row" scope="row"> {{ forloop.counter }} </th>
<td id="content">{{ all_item.content }}</td>
<form action="delete_todo/{{all_item.id}}/" method="post">
{% csrf_token %}
<td class="text-right-delete">
<button id="btn-delete" class="btn btn-outline-danger">Delete</button>
</td>
</form>
<td><a class="btn btn-outline-info" href="{% url 'todo:update' all_item.id %}">Edit</a></td>
</tr>
{% endfor %}
</tbody>
</table>
更新.html
{% extends 'html/main.html' %}
{% load static %}
{% block content %}
<form action="", method="POST">
{% csrf_token %}
{{form}}
<input type="submit" name="Submit">
</form>
{% endblock %}
但是當我運行代碼時,它顯示了這個錯誤 TypeError: UpdateContent() got an unexpected keyword argument 'instance'
將不勝感激任何回應或建議。謝謝!
uj5u.com熱心網友回復:
這是因為您的表單和視圖具有相同的名稱。所以視圖本身被遞回呼叫。
def UpdateContent(請求,pk):
內容 = todo.objects.get(id=pk)
形成= UpdateContent(例如=內容)
如果 request.method == 'POST':
form = UpdateContent (request.POST, instance=contents)
如果 form.is_valid():
表單.save()
回傳重定向('/')
背景關系 = {'形式':形式}
回傳渲染(請求,'html/update.html',背景關系)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364055.html
上一篇:Django回圈遍歷未顯示的專案
