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
  • 1
    I'm not sure what you mean by "text-only". Do you want it so that it displays it, but you cannot edit the value of name_slug?
    – bchang
    Jun 15, 2009 at 23:25
  • well both cases should work fine but, i also like a plain text alternative if it's possible Jun 19, 2009 at 15:51

1 Answer 1

2

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.