Django - 必须是str,而不是int

时间:2017-10-31 10:40:27

标签: python django filter

我得到一个有趣的例外。

如果我有这样的代码:

{% if page_nr != 0 %}
    <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a>
{% endif %}
{%page_not_over_amount page_nr amount_comments limit_amount_comment%}
{% if  comment_not_over_amount %}
    <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a>
{% endif %}

我会得到一个例外: 模板渲染期间出错 在模板C:\ Users \ Nutzer \ PycharmProjects \ selfTry \ post \ templates \ post \ comment_block.html中,错误在行 必须是str,而不是int

第22行

<a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a>

但是,如果我删除自定义标记,请将代码设为:

{% if page_nr != 0 %}
    <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a>
{% endif %}

{% if  comment_not_over_amount %}
    <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a>
{% endif %}

异常消失了! 这是我的自定义标记和过滤条件:

@register.inclusion_tag('post/comment_block.html')
def page_not_over_amount(page_nr, comment_amount, comment_limit):
    result = page_nr * comment_limit < comment_amount - comment_limit
    return {'comment_not_over_amount': result} 

@register.filter(name='increase')
def increase_variable(value, increase):
    data = value + increase
    return data

@register.inclusion_tag('post/comment_block.html')
def limit_amount_in_a_page(page_nr, topic_id=1, amount=5):
    topic = get_object_or_404(Topic,id=topic_id)
    comments = Comment.objects.filter(topic=topic)
    selected_comments = []
    starting_index = page_nr*amount
    for index in range(starting_index, starting_index + amount):
        if index >= len(comments):
            break;
        selected_comments.append(comments[index])
    return {
        'topic': topic,
        'page_nr': page_nr,
        'selected_comments': selected_comments,
        'amount_comments': comments.all().count(),
        'limit_amount_comment': amount,
    }

其他观点:

def index(request):
    all_topics = Topic.objects.all()
    context = {
        'my_topics': all_topics,
    }
    return render(request, 'post/index.html', context)


def detail(request, topic_id, page_nr):
    topic = get_object_or_404(Topic, id=topic_id)
    form = CommentForm()
    comments = Comment.objects.filter(topic=topic)

    return render(request, 'post/detail.html', {
        'topic': topic,
        'form': form,
        'comments': comments,
        'page_nr': int(page_nr),
    })


@csrf_protect
def comment(request, topic_id, user_id):
    # if this is a POST request we need to process the form data
    topic = get_object_or_404(Topic, id=topic_id)
    # try:
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CommentForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            text = form.cleaned_data['comment']
            args = {'form': form, 'topic': topic}
            # save the data in database
            save_comments_into_database(topic, int(user_id), text)
            # redirect to a new URL:
            return HttpResponseRedirect('../..', args)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CommentForm()
        return render(request, 'post/detail.html', {'form': form, 'topic': topic})

以下是所有追溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/post/1/0/

Django Version: 1.11.3
Python Version: 3.6.2
Installed Applications:
['post.apps.PostConfig',
 'music.apps.MusicConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template             C:\Users\Nutzer\PycharmProjects\selfTry\post\templates\post\comment_block.html,     error at line 22
   must be str, not int   

Traceback:

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-    packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Nutzer\PycharmProjects\selfTry\post\views.py" in detail
  27.         'page_nr': int(page_nr),

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  207.                     return self._render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
 990.                 bit = node.render_annotated(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\library.py" in render
  245.         return t.render(new_context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  209.                 return self._render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

ile "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\library.py" in render
  245.         return t.render(new_context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  209.                 return self._render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  322.                 return nodelist.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render
  441.         args = [arg.resolve(context) for arg in self.args]

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in <listcomp>
  441.         args = [arg.resolve(context) for arg in self.args]

File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in resolve
  736.                 new_obj = func(obj, *arg_vals)

File "C:\Users\Nutzer\PycharmProjects\selfTry\post\templatetags\post_filters.py" in increase_variable
  10.     data = value + increase

Exception Type: TypeError at /post/1/0/
Exception Value: must be str, not int

2 个答案:

答案 0 :(得分:0)

File "C:\Users\Nutzer\PycharmProjects\selfTry\post\templatetags\post_filters.py" in increase_variable
  10.     data = value + increase

这是引发TypeError的地方我在page_not_over_amount方法中没有看到这一点,所以你必须手动调试它。

答案 1 :(得分:0)

你必须转换为int

data = int(value) + int(increase)