Alex Stewart
Alex Stewart

Reputation: 748

Django Admin escaping text

I recently upgraded Django from 1.3 to 1.8.18 and been having issues with links custom made to pre-fill forms in Django admin. For example, I have the following link:

/admin/miscellaneous/whatsnew/add/?title=...%20competition%20results%20uploaded&pub_date=21-04-2017&body=&link=

When executed the pre-filled data in the form looks like: enter image description here

Where it should look like this:

enter image description here

When testing directly from the URL bar in Safari it changes to this after pressing enter:

https://flyball.org.au/admin/miscellaneous/whatsnew/add/?title=...%2520competition%2520results%2520uploaded&pub_date=21-04-2017&body=&link=

models.py

class WhatsNew(models.Model):
    title = models.CharField(max_length=100,help_text='Title, MAX 100 characters.')
    body = models.TextField()
    pub_date = models.DateField()
    message_expiry = models.DateField(default=datetime.date.today() + relativedelta(years=1))
    link = models.URLField(blank=True, null=True)

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = "Whats New?"

    def __unicode__(self):
        return self.title

admin.py

import models
from django.contrib import admin

class WhatsNewAdmin(admin.ModelAdmin):
    list_display = ('title','pub_date','message_expiry','link','body')

admin.site.register(models.WhatsNew, WhatsNewAdmin)

What can I do to resolve this?

Upvotes: 2

Views: 297

Answers (2)

MOHRE
MOHRE

Reputation: 1156

Use + instead of %20 for space and it works.

Your link should be something like:

/admin/miscellaneous/whatsnew/add/?title=...+competition+results+uploaded&pub_date=21-04-2017&body=&link=

Upvotes: 1

wholevinski
wholevinski

Reputation: 3828

So, I'm not sure how to do it on the ModelAdmin, but you can create custom setters on your model to handle this situation. Here's how I would go about escaping the URL encoded strings:

import urllib


class WhatsNew(models.Model):
    # Field with custom setter
    _title = models.CharField(max_length=100,
                             help_text='Title, MAX 100 characters.',
                             db_column='title')

    body = models.TextField()
    pub_date = models.DateField()
    message_expiry = models.DateField(default=datetime.date.today() + relativedelta(years=1))
    link = models.URLField(blank=True, null=True)

    # Custom getter and setter
    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = urllib.unquote(value)

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = "Whats New?"

    def __unicode__(self):
        return self._title

Upvotes: 2

Related Questions