渲染视图在模板中包含 django 位置字段
Posted
技术标签:
【中文标题】渲染视图在模板中包含 django 位置字段【英文标题】:Render view contain django location field in template 【发布时间】:2016-07-27 17:17:20 【问题描述】:我编写了一个应用程序,允许用户在地图中添加和编辑泵站及其位置。 我已经下载并安装了 caioariede/django-location-field
问题是,当我在没有位置字段的情况下渲染视图时一切正常,但是当我添加它时,我得到TemplateDoesNotExist
异常错误。
那是我的模板 add_station.html:
% extends "backend/main/base.html" %
% load i18n %
% load staticfiles %
% load forms_tags %
% block title %meta_keyword% endblock %
% block meta_keywords %meta_keyword% endblock meta_keywords %
% block meta_description %meta_description% endblock meta_description %
% block dash_title %
<i class="ppsmsite ppsmsite-station-service"></i> % trans "Station" %
% endblock %
% block dash_main %
% include "backend/main/snippets/required_fields_infos.html" %
% include "backend/main/snippets/alerts_messages.html" %
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">% trans "Enregistrer une nouvelle station" %</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" enctype="multipart/form-data">
% csrf_token %
form
<div class="form-group">
<div class="col-lg-6">
% form_div_row form.nom_station %
</div>
<div class="col-lg-6">
% form_div_row form.telephone %
</div>
</div>
<div class="form-group">
<div class="col-lg-12">
% form_div_row form.location %
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
% form_div_row form.city %
</div>
<div class="col-lg-6">
% form_div_row form.photo_station %
</div>
</div>
<div class="form-group">
<div class="col-lg-12">
<button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-check"></i> % trans "Enregistrer" %</button>
</div>
</div>
</form>
</div>
</div>
</div>
% endblock %
% block add_scripts %
form.media
% endblock add_scripts %
我的模特:
class Station(models.Model):
"""Station service."""
OPEN = 1
CLOSE = 0
STATUTLIST = (
(OPEN, _("Ouverte")),
(CLOSE, _("Fermée")),
)
nom_station = models.CharField(
_('Nom de la station'), max_length=30)
statut_station = models.CharField(
_('Ouverte ou fermée'),
max_length=1,
choices=STATUTLIST, default=OPEN)
city = models.ForeignKey(City, verbose_name=_('Ville'))
location = PlainLocationField(
based_fields=['city'], zoom=7)
photo_station = models.ImageField(
_("Photo"),
upload_to=utils.photo_file_path,
storage=utils.photo_storage,
null=True,
blank=True,
)
telephone = PhoneNumberField(_('Numero de téléphone'), null=True)
我的表格:
class StationForm(forms.ModelForm):
"""Docstring for StationsForm."""
def __init__(self, *args, **kwargs):
"""Form Init."""
self.request = kwargs.pop('request', None)
super(StationForm, self).__init__(*args, **kwargs)
for field in self.fields:
if self.fields[field] is not None:
self.fields[field].widget.attrs['class'] = 'form-control'
class Meta:
"""Docstring for StationForm meta."""
model = sitemodels.Station
fields = [
'telephone',
'photo_station', 'location', 'city', 'nom_station']
我的观点:
def add_station_view(request, station_id=None):
"""Ajout et modification d'une station."""
template_name = "backend/main/add_station.html"
args =
args.update(csrf(request))
args['meta_keyword'] = args['home_title'] = _('Station')
args['meta_description'] = _('Création d\'une nouvelle station.')
if station_id is not None:
args['cobject'] = get_object_or_404(
sitemodels.Station, id=station_id)
args['meta_description'] = _(
'Editer %s' % (args['cobject'].get_nom_station()))
form = siteforms.StationForm(
request=request,
instance=args['cobject']
)
if request.method == 'POST':
if 'cobject' in args and form.has_changed():
form = siteforms.StationForm(
request.POST,
request=request,
instance=args['cobject'])
args['updated'] = True
else:
new_station = sitemodels.Station()
form = siteforms.StationForm(
request.POST,
request=request,
instance=new_station)
if form.is_valid():
obj = form.save(commit=False)
obj.save()
if 'updated' in args:
messages.success(request, STDUMSG)
else:
obj.cree_parking()
obj.cree_catalogue()
messages.success(
request, _('Nouvelle station ajoutée'))
if 'save_and_add_another' in request.POST:
return HttpResponseRedirect(
reverse(
'ppsmsite:addstation',
current_app=request.resolver_match.namespace,
)
)
return HttpResponseRedirect(
reverse(
'ppsmsite:liststatio',
current_app=request.resolver_match.namespace,
)
)
else:
if 'cobject' not in args:
form = siteforms.StationForm(request=request)
args['form'] = form
return render_to_response(
template_name,
args,
context_instance=RequestContext(request)
)
这是我尝试渲染视图时遇到的错误:
TemplateDoesNotExist at /station/ajouter/
backend/main/add_station.html
Request Method: GET
Request URL: http://localhost:8000/station/ajouter/
Django Version: 1.8.7
Exception Type: TemplateDoesNotExist
Exception Value:
backend/main/add_station.html
Exception Location: C:\Python34\lib\site-packages\django\template\loader.py in render_to_string, line 137
Python Executable: C:\Python34\python.exe
Python Version: 3.4.4
Python Path:
['C:\\Users\\CRESUS\\Documents\\projet\\ppsm',
'C:\\Python34\\lib\\site-packages\\django_datetime_widget-0.9.3-py3.4.egg',
'C:\\WINDOWS\\SYSTEM32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: jeu, 7 Avr 2016 02:56:52 +0100
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Users\CRESUS\Documents\projet\ppsm\templates\backend\main\add_station.html (File exists)
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\suit\templates\backend\main\add_station.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\admin\templates\backend\main\add_station.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\backend\main\add_station.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\gis\templates\backend\main\add_station.html (File does not exist)
C:\Python34\lib\site-packages\ckeditor\templates\backend\main\add_station.html (File does not exist)
C:\Python34\lib\site-packages\ckeditor_uploader\templates\backend\main\add_station.html (File does not exist)
C:\Python34\lib\site-packages\geoposition\templates\backend\main\add_station.html (File does not exist)
我需要帮助!
【问题讨论】:
TemplateDoesNotExist at /station/ajouter/backend/main/add_station.html 看来问题出在您的模板上。检查你的应用目录是否有这个templates/backend/main/add_station.html
。如果失败,请尝试仅删除位置字段,然后重试。如果可行,则需要处理位置字段的呈现。
谢谢!位置字段需要处理,但我不知道该怎么做!
【参考方案1】:
当 geodjango 拥有您所需的一切并且非常易于使用时,为什么还需要使用第三方库?
理想情况下,您的位置字段应以PointField 开头。
from django.contrib.gis.db import models
class Station(models.Model):
...
...
location = PointField()
...
objects = models.GeoManager()
现在您可以访问 vase geodjango api 并允许您执行查询以找出用户附近的泵站等。示例:
https://docs.djangoproject.com/en/1.9/ref/contrib/gis/geoquerysets/#distance-lt
Station.objects.filter(poly__distance_lt=(point, D(m=5)))
【讨论】:
感谢我的朋友们!我是 geodjango 的新手,方式是我从现在开始编程站 pomp 应用程序,我想帮助站点访问者在地图视图中获取道路,以便在您探索城市时像***飞车游戏一样进入车站!以上是关于渲染视图在模板中包含 django 位置字段的主要内容,如果未能解决你的问题,请参考以下文章