Login

URLField admin widget with View Link button

Author:
ungenio41
Posted:
May 2, 2010
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

Adds a View Link button next to the field that opens the contents of the field in a new window.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""admin.py"""
from django.contrib import admin
from django.contrib.admin.widgets import AdminURLFieldWidget
from django.db.models import URLField
from django.utils.safestring import mark_safe
from myapp.models import MyModel


class URLFieldWidget(AdminURLFieldWidget):
    def render(self, name, value, attrs=None):
        widget = super(URLFieldWidget, self).render(name, value, attrs)
        return mark_safe(u'%s&nbsp;&nbsp;<input type="button" '
                         u'value="View Link" onclick="window.'
                         u'open(document.getElementById(\'%s\')'
                         u'.value)" />' % (widget, attrs['id']))


class MyAdmin(admin.ModelAdmin):
    formfield_overrides = {
        URLField: {'widget': URLFieldWidget},
    }


admin.site.register(MyModel, MyAdmin)

More like this

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

Comments

leau2001 (on June 11, 2010):

Hi,

i tried this snippet, but i v got an error : name 'URLField' is not defined

i used django 1.1.1

what's wrong ?

thx

lo

#

leau2001 (on June 12, 2010):

i add quote on URLField :

class MyAdmin(admin.ModelAdmin): formfield_overrides = { 'URLField': {'widget': URLFieldWidget}, }

Then no error now, but not any URLFieldWidget on my admin url field...

??

#

leau2001 (on June 15, 2010):

Ok i succeed :

Here the solution for django 1.1.1

from django.contrib import admin from django.db import models from django.utils.safestring import mark_safe from myapp.models import MyModel

And all works well

lo

#

ungenio41 (on July 27, 2010):

Yes, sorry, I missed a couple imports. It's fixed now.

#

Please login first before commenting.