URLField admin widget with View Link button

 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. Add a print link to the admin to print individual record by jimmylam 5 years, 5 months ago
  2. Admin Save and view next button html by ungenio41 3 years, 11 months ago
  3. Admin Save and view next button by ungenio41 3 years, 11 months ago
  4. Submit button as a form field by roxeteer 3 years, 3 months ago
  5. Add buttons in admin forms by mamat 5 years, 7 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.

#

(Forgotten your password?)