【发布时间】:2014-11-18 17:34:45
【问题描述】:
我有一个表单,用户可以输入位置信息。我正在尝试制作一个更新表单,以便用户可以单击某个位置上的更新按钮,并且更新表单会填充该位置已经存在的数据。我遵循了 Django 文档,但我得到了一个空白屏幕。我不确定如何让它引用要更新的位置。这是我目前所拥有的。
models.py
class Location(models.Model):
# Details on location
views.py
def locations(request):
return render_to_response('locations/locations.html', {'locations': Location.objects.all() })
def location(request, location_id=1):
return render_to_response('locations/location.html', {'location': Location.objects.get(id=location_id) })
def create(request):
if request.POST:
form = LocationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin/locations/all/')
else:
form = LocationForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('locations/create_location.html', args)
def edit_location(request):
if request.POST:
form = LocationUpdate(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin/locations/all/')
else:
form = LocationUpdate()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('locations/location_update.html', args)
forms.py
from django.views.generic.edit import UpdateView
from models import Location
class LocationForm(forms.ModelForm):
class Meta:
model = Location
exclude = ('timestamp', 'updated')
class LocationUpdate(UpdateView):
model = Location
template_name_suffix = '_update_form'
url.py
url(r'^accounts/loggedin/location/update/$', 'assessments.views.edit_location'),
location_update.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="update" />
</form>
</body>
</html>
还是应该放在 location.html 中。如果我在其中添加它,我会收到 CSRF verification failed 错误
<div class="row">
<div class="col-md-4">
<dl class="dl-horizontal">
<dt>ID:</dt>
<dd>{{ location.id }}</dd>
<br />
<dt>Company:</dt>
<dd>{{ location.company }}</dd>
<dt>Address:</dt>
<dd>{{ location.address }}</dd>
<dt>Town:</dt>
<dd>{{ location.town_city }}</dd>
<dt>County:</dt>
<dd>{{ location.county }}</dd>
<dt>Telephone:</dt>
<dd>{{ location.tel }}</dd>
###### ect #####
</div>
</div>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="update" />
</form>
【问题讨论】:
-
那是你的 location_update.html 的完整代码吗?您可能不是从另一个模板扩展而来的?
-
出于测试目的,它刚刚获得了 html 标题和正文标签。一旦它工作,我会将它添加到模板中。它是否需要成为 location.html 的一部分?
-
我不明白那个回复。那是 location_update.html 的完整代码吗?如果没有,请发布完整的代码。另外,准确地解释你所看到的。你有什么显示吗?当您查看源代码时,您会看到什么?
-
编辑了问题以包含更多信息。