我的代码返回而不是空字符串我之前调用的值。我该如何解决这个问题?
模板标签:
from django.template import Library, Node, resolve_variable
from django.utils.safestring import SafeText
from django.http import QueryDict
register = Library()
"""
The tag generates a parameter string in form '?param1=val1¶m2=val2'.
The parameter list is generated by taking all parameters from current
request.GET and optionally overriding them by providing parameters to the tag.
This is a cleaned up version of http://djangosnippets.org/snippets/2105/. It
solves a couple of issues, namely:
"""
class AddGetParameter(Node):
def __init__(self, values):
self.values = values
def render(self, context):
req = resolve_variable('request', context)
params = req.GET.copy()
for key, value in self.values.items():
parameterValue=value.resolve(context)
if value == "" and type(parameterValue) is SafeText and len(parameterValue) == 0 and key in params:
del params[key]
else:
params[key] = parameterValue
resultDict=dict()
for key in params:
if len(str(params[key]))>0:
resultDict[key]=params[key]
qdict = QueryDict('', mutable=True)
qdict.update(resultDict)
urlString=qdict.urlencode()
print urlString
if len(urlString) > 0:
return '?%s' % urlString
else:
return ''
@register.tag
def add_get(parser, token):
pairs = token.split_contents()[1:]
values = {}
for pair in pairs:
s = pair.split('=', 1)
values[s[0]] = parser.compile_filter(s[1])
return AddGetParameter(values)
注意:我修改了代码段,以便从网址中删除未设置为“”的变量。
template.html:
{% load add_get_parameter %}
<a href="{% add_get location="7" %}">set</a>
<a href="{% add_get location="" %}">empty</a>
结果:
<a href="?location=7">set</a>
<a href="?location=7">empty</a>
如果我将return ''
更改为return "?"
,则结果为:
<a href="?location=7">set</a>
<a href="?">empty</a>
但是我怎么能得到一个字符串什么都没有(长度为0的字符串)?我做错了什么?
更新 settings.py:
# Django settings for Roadrunners project.
from django.core.urlresolvers import reverse_lazy
import djcelery
djcelery.setup_loader()
import os
from django.utils.translation import ugettext_lazy as _
gettext = lambda s: s
PROJECT_PATH = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]
APPLICATION_PATH=os.path.abspath('.')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(PROJECT_PATH, 'database.sqlite'), # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
TIME_ZONE = 'Europe/Vienna'
LANGUAGE_CODE = 'de'
ugettext = lambda s: s
LANGUAGES = [
('de', gettext('Deutsch')),
('en', gettext('English')),
]
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = False
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media").replace('\\','/')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = '**REMOVED**'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'crequest.middleware.CrequestMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
ROOT_URLCONF = 'Roadrunners.urls'
WSGI_APPLICATION = 'Roadrunners.wsgi.application'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'autoslug',
'debug_toolbar',
'easy_thumbnails',
'crispy_forms',
'VariousHelpers',
'django_filters',
'VerifiedDocuments',
'VMS',
'django_countries',
'multiselectfield',
'django_tables2', #// probleme mit 1.8
'django_select2', #// probleme mit 1.8
'mathfilters',
'crequest',
'Events',
'Place',
'data_importer', # // probleme mit 1.8
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
TEMPLATE_CONTEXT_PROCESSORS=(
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
)
#TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),)
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_PATH, "templates"),
os.path.join(APPLICATION_PATH, "Place"),
os.path.join(APPLICATION_PATH, "VerifiedDocuments"),
os.path.join(APPLICATION_PATH, "Events"),
)
LOGIN_REDIRECT_URL = reverse_lazy('inside')
LOGIN_URL = reverse_lazy('login')
DEFAULT_FROM_EMAIL='******REMOVED******'
THUMBNAIL_PROCESSORS = (
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
'easy_thumbnails.processors.scale_and_crop',
'easy_thumbnails.processors.filters',
'easy_thumbnails.processors.background',
)
CRISPY_TEMPLATE_PACK = 'bootstrap3'
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
)
def custom_show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
#'EXTRA_SIGNALS': ['myproject.signals.MySignal'],
'HIDE_DJANGO_SQL': False,
'TAG': 'div',
}
SELECT2_BOOTSTRAP = True
GENERATE_RANDOM_SELECT2_ID = True
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
答案 0 :(得分:0)
这实际上适合我,我得到:
<a href="?location=7">set</a>
<a href="">empty</a>
我怀疑你可能在模板中有一些缓存(块缓存)。如果没有,那么也许其他一些奇怪的事情正在弄乱你的要求。进行调试打印并查看它告诉您的内容以及它运行的次数:
def render(self, context):
req = resolve_variable('request', context)
params = req.GET.copy()
print "----"
print "\n".join("{}:{}".format(k, v) for k, v in params.items())
print "----"