Last Updated: February 25, 2016
·
1.386K
· katylava

Sanitize admin user's URL input before validation in Django

Note: I'm using urlnorm, but this
is just to show you where to hook the logic in -- you might want to use
something else.

models.py

from django.db import models

class LinkyDink(models.Model):
    url = models.URLField()

admin.py

from urlnorm import norm
from django import forms
from django.contrib import admin
from models import LinkyDink

class LinkyDinkForm(forms.ModelForm):

    def full_clean(self):
        if self.data:
            field_name = 'url' if not self.prefix \
                                else '{}-url'.format(self.prefix)
            field_value = self.data.get(field_name)
            if field_value:
                self.data[field_name] = norm(field_value.strip())
        super(LinkyDinkForm, self).full_clean()

    class Meta:
        model = LinkyDink


class LinkyDinkAdmin(admin.ModelAdmin):
    form = LinkyDinkForm
    # ... etc.


# also works with inlines (because of the prefix logic)...

class LinkyDinkInline(admin.TabularInline):
    model = LinkyDink
    form = LinkyDinkForm
    # ... etc.