Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Urlize DRF Link

I have a DRF serializer:

class ActivitySerializer(serializers.ModelSerializer):
    link = serializers.CharField(source='get_analytic_link', allow_null=True)
    class Meta:
        model = Activity
        fields = ['link',]

In the browsable API, the links are clickable. However, when they are served up to a DataTable via a JSON endpoint, they are (predictably) not clickable. In plain Django, I would do something like this:

<td>{{ activity.get_analytic_link|urlize }}</td>

How could I replicate that behavior in DRF so that links are clickable?

like image 921
OverflowingTheGlass Avatar asked Aug 29 '26 23:08

OverflowingTheGlass


1 Answers

It looks like this a job on the frontend, and you should use DataTable's columns.render feature.

Example:

var responseObj = [
    { "information": "A1", "weblink": "http://www.microsoft.com" },
    { "information": "A2", "weblink": "http://www.yahoo.com" },
    { "information": "A3", "weblink": "http://www.google.com" },
    { "information": "A4", "weblink": "http://www.duckduckgo.com" }
];

$('#example').dataTable({
   "data": responseObj,
   "columns": [
      { "data": "information" }, 
      { 
         "data": "weblink",
         "render": function(data, type, row, meta){
            if(type === 'display'){
                data = '<a href="' + data + '">' + data + '</a>';
            }

            return data;
         }
      } 
   ]
});
like image 100
Hybrid Avatar answered Sep 01 '26 16:09

Hybrid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!