这是应该更新现有模型的模板。我查看了多个教程,但我仍然不知道为什么我的表格字段没有预先填充。有没有人知道什么是错的?
我的表格:
class UpdateSiteForm(forms.ModelForm):
class Meta:
model = Site
fields = ('name', 'description', 'URL',)
我的模特:
class Site(models.Model):
name = models.CharField(max_length=255,unique=True)
description = models.TextField(default='')
URL = models.URLField(default=None)
owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None)
我的模板:
{% extends 'base.html' %}
{% block content %}
<div class="updatesite">
<h2>{{site.name}} Update-page</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Update</button>
</form>
</div>
{% endblock %}
my views.py
def updatesite(request,id):
site = get_object_or_404(Site, id=id)
dev = request.user
if request.method == 'POST':
form = UpdateSiteForm(request.POST,instance=site,initial=site)
if form.is_valid():
form.save()
return redirect('userhome')
else:
form = UpdateSiteForm()
return render(request,'updatesite.html',{'site':site, 'form': form})
答案 0 :(得分:2)
您没有传递应该从以下位置获取表单数据的实例:
def updatesite(request,id):
site = get_object_or_404(Site, id=id)
dev = request.user
if request.method == 'POST':
form = UpdateSiteForm(request.POST,instance=site,initial=site)
if form.is_valid():
form.save()
return redirect('userhome')
else:
form = UpdateSiteForm(instance=site)
return render(request,'updatesite.html',{'site':site, 'form': form})