views:

184

answers:

1

Ok for something that sounds easy, im having some problems looking for an answer. I have this model:

class Page(models.Model):
    creator       = models.TextField(blank=False)
    name        = models.CharField(max_length=70, primary_key=True)
    name_slug     = models.SlugField(max_length=70, unique=True)

whenever I save in admin im doing a pre-save operation(save_model()) that passes the slugged value of name + creator(ex: i_am_legend_cyber_valdez) to name_slug, what i want to do is completely make the name_slug textbox in admin text-only without playing around with admin templates. Is this possible?

+2  A: 

Either in your ModelAdmin.formfield_overrides, or ModelAdmin.formfield_for_dbfield, or in a custom ModelForm, you need to assign a custom widget to the name_slug field that just displays the value of the field rather than displaying an HTML form input. You can find just such a widget here.

EDIT: I won't get into the details of creating a custom widget, as you can just use the one I linked to above. To enable this widget for all SlugField's in a model, the simplest way is to use formfield_overrides:

class PageAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.SlugField: {'widget': ReadOnlyWidget},
    }

If you have multiple SlugFields in your model and only want to apply the ReadOnlyWidget to one of them, you'd override the formfield_for_dbfield method:

class PageAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'name_slug':
            kwargs['widget'] = ReadOnlyWidget
        return super(PageAdmin, self).formfield_for_dbfield(db_field, **kwargs)

You can also create a fully-custom ModelForm for your model and assign it to the form attribute of your ModelAdmin, but that isn't necessary unless you're doing deeper customizations.

Carl Meyer
Hmm can you teach me how, I've seen the widget documentation but it's not that well documented. http://docs.djangoproject.com/en/dev/ref/forms/widgets/
cybervaldez