python - Django:如何将提交的数据放回表单中(更新功能)
问题描述
我一直在尝试在我的表中创建一个“更新功能”,以便用户可以更改我的数据。
所以这是我的 html,其中包含我希望我的数据返回的表单,所以当用户再次按下提交时,它会将该值保存到数据库中:
<h3>Add a location </h3></br></br>
<div class="addition">
<form method="POST" action="" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col">
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Location name" name="name" autocomplete="off">
</div>
<div class="col">
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Description" name="desc" autocomplete="off">
</div>
<div class="col">
<button type="submit" class="btn btn-primary">Submit</button>
</div></br></br>
</form> </br></br>
<h3>Overview locations</h3>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for item in all_locations %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.name }}</td>
<td>{{ item.desc }}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'update_location' item.id %}" >update</a></td>
</tr>
我的views.py带有我的创建功能和我的更新功能
def location(request):
all_locations = Location.objects.all()
if request.method == "POST":
loc_form = LocationForm(request.POST or None)
if loc_form.is_valid():
loc_form.save()
return render(request, 'location.html', {"all_locations": all_locations})
else:
return render(request, 'location.html', {"all_locations": all_locations})
return render(request, 'location.html', {"all_locations": all_locations})
def updateLocation(request, pk):
all_locations = Location.objects.all()
location = Location.objects.get(id=pk)
loc_form= LocationForm(instance=location)
name = loc_form.instance.name
desc = loc_form.instance.desc
print(name)
print(desc)
return render(request, 'location.html', {"all_locations": all_locations, "name": name, "desc": desc})
我的模型.py
class Location(models.Model):
creation_date = models.DateTimeField(auto_now = True)
name = models.CharField(max_length=50, default=None)
desc = models.CharField(max_length=250, default="", null=True, blank=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
和我的urls.py
urlpatterns = [
path('', views.index, name="index"),
path('locations', views.location, name="location"),
path('locations/<str:pk>', views.updateLocation, name="update_location"),
]
所以基本上我坚持将旧数据放回 html 输入。我也尝试过不同的观点,但我遇到了基本相同的问题。
有什么建议么?非常感谢!
解决方案
我在做其他事情时发现了它:
添加value="{{ name }}"
到输入行的 html 文件中。做类似的事情来描述
推荐阅读
- couchbase - 从 Couchbase N1Q1 查询返回的数组中获取最小值和最大值
- python - 包安装
- xamarin.forms - 在 UWP 中,如何为自定义控件设置自动化 ID?
- postgresql - Kubernetes pod 内部无法通信
- kubernetes - pod内特定进程的GKE OOM-killer
- macos - 我在 vscode 上同步了设置和扩展,我想恢复更改
- python - 每次单击编辑器内的任何位置时,如何阻止此弹出窗口出现
- javascript - 反应选择。滚动到最后一个选项后自动加载新数据
- uwp - 获取 UWP 可选包中的包 ID
- reddit - 保存 reddit 页面以供参考