1

我的自定义标签代码是

class RatingsNode(template.Node):
def __init__(self,revschedid,tempid,empid,quesid):
    self.revschedid = template.Variable(revschedid)
    self.tempid = template.Variable(tempid)
    self.empid = template.Variable(empid)
    self.quesid = template.Variable(quesid)
def render(self, context):
    try:
        fill_answers = tbtrnappraisalanswer.objects.get(intRevSchedID_id=self.revschedid.resolve(context),intTemplateID_id=self.tempid.resolve(context),intEmpID_id__exact=self.empid.resolve(context),intQuesID_id__exact=self.quesid.resolve(context))
        return fill_answers.intEmpValue_id
    except:
        return ''

def get_rating(parser, token):
 try:
    # split_contents() knows not to split quoted strings.
    tag_name,revschedid,tempid,empid,quesid  = token.split_contents()
except ValueError:
    raise template.TemplateSyntaxError("%r tag requires four arguments" % token.contents.split()[0])
return RatingsNode(revschedid,tempid,empid,quesid)
register.tag('get_rating_question',get_rating)

我的模板代码是

<span class="input-group-addon">
{% if  get_rating_question  schedid  tempid user.id question.intQuesID  == rating.intRatingValue %}
<input type="radio" name="fill_apraisal_rating{{ question.intQuesID }}" value="{{ rating.intRatingValue }}" checked='checked'>                                       
 {% else %}
 <input type="radio" name="fill_apraisal_rating{{ question.intQuesID }}" value="{{ rating.intRatingValue }}">
 {% endif %}
 </span>

上面的代码引发了一个错误环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/opas/fill_appraisal/5/2/

Django Version: 1.5.4
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'csvimport',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'employees',
 'schdeules',
 'crispy_forms')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Template error:
In template C:\pythonprgs\opas\schdeules\templates\schdeules\fill_appraisal.html, error at line 37
   Unused 'schedid' at end of if expression.
   27 :    {% endif %}
   28 :                        
   29 :    {% if question.enumRating == "1" %}
   30 :        <br>
   31 :        <div class="input-group">
   32 :            {% for rating in ratings %}
   33 :                {% ifnotequal rating.intRatingValue 0 %}
   34 :                                       
   35 :                                         
   36 :                    <span class="input-group-addon">
   37 :                    {% if  get_rating_question  schedid  tempid user.id question.intQuesID  == rating.intRatingValue %} 
   38 :                        <input type="radio" name="fill_apraisal_rating{{ question.intQuesID }}" value="{{ rating.intRatingValue }}" checked='checked'>
   39 :                                           
   40 :                    {% else %}
   41 :                        <input type="radio" name="fill_apraisal_rating{{ question.intQuesID }}" value="{{ rating.intRatingValue }}">
   42 :                    {% endif %}
   43 :                    </span>
   44 :                    {{ rating.intRatingValue }}
   45 :                                         
   46 :                {% endifnotequal %}
   47 :            {% endfor %}


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "C:\pythonprgs\opas\schdeules\views.py" in fillappraisal
  39.     return render(request, 'schdeules/fill_appraisal.html',context)
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py" in render
  53.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  170.         t = get_template(template_name)
File "C:\Python27\lib\site-packages\django\template\loader.py" in get_template
  146.     template, origin = find_template(template_name)
File "C:\Python27\lib\site-packages\django\template\loader.py" in find_template
  135.             source, display_name = loader(name, dirs)
File "C:\Python27\lib\site-packages\django\template\loader.py" in __call__
  43.         return self.load_template(template_name, template_dirs)
File "C:\Python27\lib\site-packages\django\template\loader.py" in load_template
  49.             template = get_template_from_string(source, origin, template_name)
File "C:\Python27\lib\site-packages\django\template\loader.py" in get_template_from_string
  157.     return Template(source, origin, name)
File "C:\Python27\lib\site-packages\django\template\base.py" in __init__
  125.         self.nodelist = compile_string(template_string, origin)
File "C:\Python27\lib\site-packages\django\template\base.py" in compile_string
  153.     return parser.parse()
File "C:\Python27\lib\site-packages\django\template\base.py" in parse
  274.                     compiled_result = compile_func(self, token)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in do_extends
  215.     nodelist = parser.parse()
File "C:\Python27\lib\site-packages\django\template\base.py" in parse
  274.                     compiled_result = compile_func(self, token)
File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in do_block
  190.     nodelist = parser.parse(('endblock',))
File "C:\Python27\lib\site-packages\django\template\base.py" in parse
  274.                     compiled_result = compile_func(self, token)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in do_for
  769.     nodelist_loop = parser.parse(('empty', 'endfor',))
File "C:\Python27\lib\site-packages\django\template\base.py" in parse
  274.                     compiled_result = compile_func(self, token)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in do_if
  905.     nodelist = parser.parse(('elif', 'else', 'endif'))
File "C:\Python27\lib\site-packages\django\template\base.py" in parse
  274.                     compiled_result = compile_func(self, token)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in do_for
  769.     nodelist_loop = parser.parse(('empty', 'endfor',))
File "C:\Python27\lib\site-packages\django\template\base.py" in parse
  274.                     compiled_result = compile_func(self, token)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in ifnotequal
  819.     return do_ifequal(parser, token, True)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in do_ifequal
  783.     nodelist_true = parser.parse(('else', end_tag))
File "C:\Python27\lib\site-packages\django\template\base.py" in parse
  274.                     compiled_result = compile_func(self, token)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in do_if
  904.     condition = TemplateIfParser(parser, bits).parse()
File "C:\Python27\lib\site-packages\django\template\smartif.py" in parse
  191.                                    self.current_token.display())

Exception Type: TemplateSyntaxError at /opas/fill_appraisal/5/2/
Exception Value: Unused 'schedid' at end of if expression.

如果从自定义模板标签返回的值等于单选按钮值,我想检查单选按钮。提前致谢。

4

3 回答 3

2

Django 的模板语言不是 Python,模板标签也不是函数,所以{% if get_rating_question schedid tempid user.id question.intQuesID == rating.intRatingValue %}jus 是行不通的。您在这里需要的是让您的模板标签在上下文中设置一个变量,然后针对这个变量进行测试,即:

{% get_rating_question  schedid  tempid user.id question.intQuesID as whatever %}
{% if rating.intRatingValue == whatever %}
# do something here
{% endif %}

您可以在此处阅读有关更新上下文的 FineManual(tm):https ://docs.djangoproject.com/en/1.5/howto/custom-template-tags/#setting-a-variable-in-the-context - 以及关于在此处编写分配标签的一种更简单的方法:https ://docs.djangoproject.com/en/1.5/howto/custom-template-tags/#assignment-tags

或者您确实可以让您的模板标签rating.intRatingValue进行测试并返回适当的字符串,但它会不太灵活。

附带说明:在您的模板标签的代码中,您有一个简单的 expect 子句。帮自己一个忙并修复它以仅捕获预期的异常。

于 2013-11-07T09:26:57.200 回答
1

如果要在 if 条件下使用某些操作,请在 django 中使用 Filter

例如:
{%if course|user_is_owner %}
<div class="col-md-6">
<a href="/course/action/{{course.course_uuid}}/" class="btn-danger">Delete</a>
</div>
{%endif%}

于 2015-07-29T11:45:22.653 回答
0

只需传递rating.intRatingValue给标签,如果满足条件,则使标签返回一个字符串checked="checked",否则返回一个空字符串。然后将其放入模板中:

<input type="radio" name="fill_apraisal_rating{{ question.intQuesID }}" 
value="{{ rating.intRatingValue }}" 
{% get_rating_question schedid tempid user.id question.intQuesID, rating.intRatingValue %}>                                       

PS Asimple_tag在这里可能是一个更好的选择。

于 2013-11-07T08:25:19.073 回答