Django-rest-framework: Errors in rendering form

Created on 9 Mar 2016  路  13Comments  路  Source: encode/django-rest-framework

I'm using rest framework version 3.3.2. At loading form by serializer with rest framework template tag method render_form, while django logger has been activated in console, i catch some bad errors in checking style attributes in rest_framewok/templates/rest_framework/vertical/ files.
For example, I have pasted a piece of these errors below:

DEBUG Exception while resolving variable 'hide_label' in template 'rest_framework/vertical/input.html'.
Traceback (most recent call last):  
  File "/home/m.emami/.env/myenv/lib/python3.4/site-packages/django/template/base.py", line 879, in _resolve_lookup
    current = current[bit]
KeyError: 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):  
  File "/home/m.emami/.env/myenv/lib/python3.4/site-packages/django/template/base.py", line 887, in _resolve_lookup
    current = getattr(current, bit) 
AttributeError: 'dict' object has no attribute 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):  
  File "/home/m.emami/.env/myenv/lib/python3.4/site-packages/django/template/base.py", line 894, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'hide_label'

During handling of the above exception, another exception occurred:

...
Needs further review

Most helpful comment

+1, I'm also seeing this.

All 13 comments

The next step here would be to get a failing test case we could run to illustrate the issue.

Run this script in your virtualenv to get feedback

import os, sys

# comment lines below if you run the code in root of your django application
directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, directory)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings.local")

import django
from rest_framework import serializers
import logging
from rest_framework.templatetags import rest_framework as rf_template_tags

django.setup()
logger = logging.getLogger('myproject')


class RegistrationSerializer(serializers.Serializer):
    first_name = serializers.CharField(max_length=40, label='First Name')

print(rf_template_tags.render_form(RegistrationSerializer()))

My feedback

(myprojectenv)[m.emami@voip scripts]$ python test1.py
DEBUG Exception while resolving variable 'hide_label' in template 'rest_framework/vertical/input.html'.
Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 883, in _resolve_lookup
    current = current[bit]
KeyError: 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 891, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'dict' object has no attribute 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 898, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 905, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [hide_label] in "{'renderer': <rest_framework.renderers.HTMLFormRenderer object at 0x7ff05917c240>, 'template_pack': 'rest_framework/vertical/', 'input_type': 'text', 'base_template': 'input.html'}"
DEBUG Exception while resolving variable 'placeholder' in template 'rest_framework/vertical/input.html'.
Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 883, in _resolve_lookup
    current = current[bit]
KeyError: 'placeholder'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 891, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'dict' object has no attribute 'placeholder'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 898, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'placeholder'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/myprojectenv/lib/python3.4/site-packages/django/template/base.py", line 905, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [placeholder] in "{'renderer': <rest_framework.renderers.HTMLFormRenderer object at 0x7ff05917c240>, 'template_pack': 'rest_framework/vertical/', 'input_type': 'text', 'base_template': 'input.html'}"
    <div class="form-group ">
    <label > First Name</label>
  <input name="first_name" class="form-control" type="text"  >
</div>

@emamirazavi unfortunately, this doesn't fail here:

python manage.py shell
Python 3.5.1 (default, Dec 15 2015, 19:31:28) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from rest_framework import serializers
>>> import logging
>>> from rest_framework.templatetags import rest_framework as rf_template_tags
>>> class RegistrationSerializer(serializers.Serializer):
...     first_name = serializers.CharField(max_length=40, label='First Name')
... 
>>> print(rf_template_tags.render_form(RegistrationSerializer()))
/Users/xordoquy/.local/share/virtualenvs/eed46573b510bc8/lib/python3.5/site-packages/django/template/utils.py:37: RemovedInDjango110Warning: You haven't defined a TEMPLATES setting. You must do so before upgrading to Django 1.10. Otherwise Django will be unable to load templates.
  "unable to load templates.", RemovedInDjango110Warning)




    <div class="form-group ">

    <label >First Name</label>


  <input name="first_name" class="form-control" type="text"  >




</div>




>>> 

Versions:

$ pip freeze -l
Django==1.9.4
djangorestframework==3.3.2

@xordoquy unfortunately you must turn your logger on in your setting like below:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        # 'special': {
        #     '()': 'project.logging.SpecialFilter',
        #     'foo': 'bar',
        # },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.FileHandler',
            'filename': '/tmp/myproject.log',
            'formatter': 'verbose'
        },
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'myproject': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

In development process have not you ever run django in debug mode with active loggers?!!!

versions:

Django==1.9.4
djangorestframework==3.3.2

Please open this issue to help to resolve the problem. Why did you close it without any feedback sent by me?!!!

@emamirazavi You have the explanation why I closed the bug in the comment.
Reopening this as indeed the logging configuration was incomplete.
For the record, I usually don't have logging for dev. I configure the logging for tests only.

+1, I'm also seeing this.

Thanks @jamesbeith. Anyone able to confirm if this is now resolved?

@tomchristie Yes, I did it and the error still exists. The error is vivid. style key of context created by serializers of rest framework has no default values for such attributes like hide_label and placeholder. This is about rest_framework/vertical/input.html file. It may other form templates generate some other errors. See logs of above test case with Django==1.10 and djangorestframework==3.4.4:

DEBUG 2016-08-15 14:07:08,242 base 16544 139695390242560 Exception while resolving variable 'hide_label' in template 'rest_framework/vertical/input.html'.
Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 885, in _resolve_lookup
    current = current[bit]
KeyError: 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 893, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'dict' object has no attribute 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 900, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'hide_label'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 907, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [hide_label] in "{'template_pack': 'rest_framework/vertical/', 'input_type': 'text', 'base_template': 'input.html', 'renderer': <rest_framework.renderers.HTMLFormRenderer object at 0x7f0d4d5bbfd0>}"
DEBUG 2016-08-15 14:07:08,242 base 16544 139695390242560 Exception while resolving variable 'placeholder' in template 'rest_framework/vertical/input.html'.
Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 885, in _resolve_lookup
    current = current[bit]
KeyError: 'placeholder'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 893, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'dict' object has no attribute 'placeholder'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 900, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'placeholder'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m.emami/.env/pakanenv/lib/python3.4/site-packages/django/template/base.py", line 907, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [placeholder] in "{'template_pack': 'rest_framework/vertical/', 'input_type': 'text', 'base_template': 'input.html', 'renderer': <rest_framework.renderers.HTMLFormRenderer object at 0x7f0d4d5bbfd0>}"

I'm also having this issue. Pages of log output in the shell. Will now change the Django logger log level to INFO (I just upgraded from 1.8 to 1.11, and 1.8 didn't log these warnings by default), but would be great if we could find a fix for this.

issue still there with drf version 3.6.4. logging level is DEBUG

This isn't a bug.

The various templates have various additional style options as documented on HTML & Forms topic page.

The exception, django.template.base.VariableDoesNotExist, is just Django's default handling of undefined variables in templates. The whole point is that setting logging to DEBUG means you see some (? a lot) of extra noise.

The _solution_ here is to configure the relevant django.* sub-logger to filter these messages. (They're expected. We're leveraging a known behaviour.)

Was this page helpful?
0 / 5 - 0 ratings