Login

URLMan serializer field for Django Rest Framework (DRF)

Author:
rixx
Posted:
August 13, 2019
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

This snippet shows how to add a url field to your API objects, which will then show up as an object in your JSON output.

As parameters, you can specify:

  • urls: A list of strings that exist on your URLMan class
  • attribute: The name of the URLMan class on your model, defaults to "urls"
  • full: If the full URLs including schema and hostname should be supplied, defaults to True
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from rest_framework.serializers import Field


class URLManField(Field):

    read_only = True
    write_only = False
    label = None
    source = '*'

    def __init__(self, *, urls, attribute='urls', full=True):
        self.urls = urls
        self.url_class = attribute
        self.full = full

    def to_representation(self, value):
        url_class = getattr(value, self.url_class)
        return {
            url: getattr(url_class, url).full() if self.full else getattr(url_class, url)
            for url in self.urls
        }

class MySerializer(ModelSerializer):
    urls = URLManField(urls=['login', 'logout', 'base'])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.