0

I want to use the rest framework api to render the json data from the list method and the form from the post in a template. I have been searching in the rest-framework docs for the renderer clases, Html rendering and form rendering but came to no solution. This is the relevant code

//models.py
class Collaborator(models.Model):
    user = models.OneToOneField(User,
                                related_name='collaborator',
                                on_delete=models.CASCADE
                                )
    area = models.ForeignKey(Area,
                             verbose_name=_('Área del colaborador'),
                             related_name='collaborator'
                             )
    position = models.ForeignKey(Position,
                                 verbose_name=_('Cargo del Colaborador'),
                                 related_name='collaborator'
                                 )
    photo = models.ImageField(_('Fotografía del colaborador'),
                              null=True,
                              blank=True,
                              help_text=_('Fotografía del Colaborador'),
                              )
    birth_date = models.DateField(_('Fecha de Nacimiento'),
                                  null=True,
                                  blank=True
                                  )
    join_date = models.DateField(_('Fecha de Ingreso'),
                                 null=True,
                                 blank=True
                                 )
    payment = models.DecimalField(_('Sueldo'),
                                  max_digits=8,
                                  decimal_places=4,
                                  null=True,
                                  blank=True
                                  )
    fire_reason = models.TextField(_('Razón de despido / renuncia'),
                                   blank=True,
                                   null=True,
                                   help_text=_('Detallar la razón de por qué salió el colaborador.')
                                   )

    class Meta:
        ordering = (
            'id',
            'user',
            'area',
            'birth_date',
            'join_date',
            'payment',
        )
        verbose_name = _('Colaborador')
        verbose_name_plural = _('Colaboradores')

    def __unicode__(self):  # __unicode__ on Python 2
        return '%s %s' % (self.user.first_name,
                          self.user.last_name
                          )
//serializers.py

class UserSerializer(ModelSerializer):
class Meta:
    model = User
    fields = (
        'username',
        'password',
        'first_name',
        'last_name',
        'email',
        'groups',
        'is_active'
    )


class CollaboratorSerializer(ModelSerializer):
    user = UserSerializer(many=False)

    class Meta:
        model = Collaborator
        fields = (
            'id',
            'user',
            'photo',
            'area',
            'position',
            'birth_date',
            'payment',
            'join_date',
            'fire_reason',
        )

    position = StringRelatedField(many=False)
    area = StringRelatedField(many=False)

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(**validated_data)
        User.objects.create(user=user, **user_data)
        return user

//views (rest framework view)
class CollaboratorViewSet(viewsets.ModelViewSet):
    """
    A viewset for viewing and editing user instances.
    """
    serializer_class = CollaboratorSerializer
    queryset = Collaborator.objects.all()

//urls.py
urlpatterns = [
    url(r'^collaborators-list/$',


CollaboratorViewSet.as_view({'get':'list','post':'create','delete':'destroy','put':'update'}),
    name='collaborators-list'
    ),
]

This is the traceback error

Traceback (most recent call last):
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
    response = get_response(request)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response
    response = self.process_exception_by_middleware(e, request)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response
    response = response.render()
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\template\response.py", line 109, in render
    self.content = self.rendered_content
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\rest_framework\renderers.py", line 176, in render
    return template_render(template, context, request=request)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\rest_framework\compat.py", line 332, in template_render
    return template.render(context, request=request)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\template\backends\django.py", line 64, in render
    context = make_context(context, request, autoescape=self.backend.engine.autoescape)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\template\context.py", line 267, in make_context
    context.push(original_context)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\template\context.py", line 59, in push
    return ContextDict(self, *dicts, **kwargs)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\template\context.py", line 18, in __init__
    super(ContextDict, self).__init__(*args, **kwargs)
    ValueError: dictionary update sequence element #0 has length 9; 2 is required
    [27/Apr/2017 08:45:30] "GET /es/gdh/collaborators-list/ HTTP/1.1" 500 107315

Edit 2

Removing this from the url {'get':'list','post':'create','delete':'destroy','put':'update'}, I get this error.

Traceback (most recent call last):
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
    response = get_response(request)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\utils\deprecation.py", line 138, in __call__
    response = self.process_response(request, response)
    File "D:\PROGRAMACION\VENVS\gutenberg\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response
    if response.get('X-Frame-Options') is not None:
    AttributeError: 'function' object has no attribute 'get'
    [27/Apr/2017 09:47:21] "GET /es/gdh/collaborators-list/ HTTP/1.1" 500 63775
Dharien Cthaeh
  • 67
  • 2
  • 10
  • Do you mean that you want to pass a serialzied data generated by drf to your regular django template? Just wanna make it clear thanks\ – Shift 'n Tab Apr 27 '17 at 13:49
  • I have seen in the docs that you can render the form, in fact, you can render the whole json and form in a template. I want to do that too to reduce code and let drf handle the saving and stuff. But the most important thing, if that is not possible, is to pass a json to my template. Am I making any sense? Sorry if I make mistakes, english is my second language and I am still learning. – Dharien Cthaeh Apr 27 '17 at 14:12
  • Can you post the doc you have seen? sounds like you wanted to render the whole the drf template to your app right? I dont know it that is possible but drf api template is just to view your serialized response data. – Shift 'n Tab Apr 27 '17 at 14:16
  • Yes of course. This is one [link](http://www.django-rest-framework.org/api-guide/renderers/#htmlformrenderer) and this is the other [link](http://www.django-rest-framework.org/topics/html-and-forms/) – Dharien Cthaeh Apr 27 '17 at 14:20
  • Yes you are right you can truly render the serialized data as a form but the doc somewhat lacking an example – Shift 'n Tab Apr 27 '17 at 14:29
  • In my code I have set a ModelViewSet and I am trying to make it work. But I get this error. ValueError: dictionary update sequence element #0 has length 9; 2 is required – Dharien Cthaeh Apr 27 '17 at 14:32
  • you can take a lot at this http://stackoverflow.com/questions/14302248/dictionary-update-sequence-element-0-has-length-3-2-is-required it is a sequence structure problem or you can remove this `{'get':'list','post':'create','delete':'destroy','put':'update'}` because it is somewhat redundant – Shift 'n Tab Apr 27 '17 at 14:37

0 Answers0