Solved: customise django admin edit model button in field

The main problem is that customising the django admin edit model button in a field can lead to unexpected behaviour.


I have a model with a foreign key to another model. In the admin view, I want to customise the edit button for this field.
In my admin.py:
<code>class MyModelAdmin(admin.ModelAdmin):

    def edit_button(self, obj):
        return '&lt;a href="/myapp/mymodel/%s"&gt;edit&lt;/a&gt;' % obj.id

    edit_button.allow_tags = True
    edit_button.short_description = 'Edit'

    list_display = ('name', 'edit_button')
</code>
This works fine and gives me an "edit" link in the column for each row of my list view, but it links to /myapp/mymodel/1 instead of /admin/myapp/mymodel1/. How can I make it link to the admin page?


A:

You can use <code>reverse()</code>:  https://docs.djangoproject.com/en/dev/_modules/django/core/urlresolvers/#reverse  (or <code>urlresolvers</code>, which is what reverse is imported as)   It will automatically generate urls based on your urls file and any named url patterns you have defined in there (like <code>admin:index</code>)  So you could do something like this:   (I'm assuming your app name is "foo")     If not, just change it accordingly in the code below...   Also note that I've changed your function name from <code>edit_button()</code> to <code>get_edit_link()</code>.  This is because Django uses methods starting with get as accessors for fields in a model class...  So if you don't change it, Django will try and call that method on your model class instead of on your ModelAdmin class...   Which won't work because there's no such method defined on your model class...     Anyway, here's how you could do it:   (Note that I've also added an import statement at the top)     Also note that I've changed your function name from <code>edit_button()</code> to <code>get_edit_link()</code>.  This is because Django uses methods starting with get as accessors for fields in a model class...  So if you don't change it, Django will try and call that method on your model class instead of on your ModelAdmin class...   Which won't work because there's no such method defined on your model class...     Anyway, here's how you could do it:       (Note that I've also added an import statement at the top)      Also note that I've changed your function name from edit button () To get edit link (). Because django uses methods starting with get as accessors for fields in a model Class ... so if You don't change It , django Will Try And Call That Method On Your Model Class Instead Of On Your Model Admin Class ... which Won't Work Because There Is No Such Method Defined On Your Model Class ... anyway , Here Is How You Could Do It :      ( Note That i Have Also Added An Import Statement At The Top )       Also Note That i Have Changed Your Function Name From Edit Button () To Get Edit Link (). Because django Uses Methods Starting With Get As Accessors For Fields In A Model Class ... so if You Don't Change It , django Will Try And Call That Method On Your Model Class Instead Of On Your Model Admin Class ... which Won't Work Because There Is No Such Method Defined On Your Model Class ... anyway , Here Is How You Could Do It :       ( Note That i Have Also Added An Import Statement At The Top )        Also Note That i Have Changed Your Function Name From Edit Button () To Get Edit Link (). Because django Uses Methods Starting With Get As Accessors For Fields In A Model Class ... so if You Don't Change It , django Will Try And Call That Method On Your Model Class Instead Of On Your Model Admin Class ... which Won't Work Because There Is No Such Method Defined On Your Mode lClass . .. anyway , Here Is How You Could Do It :        ( Note That i Have Also Added An Import Statement At The Top )         also note that i have changed y our function name from edit button () To get e dit l ink (). B ecause d jango u ses m ethods s taring w ith g et a s a ccessors f or f ields i n a m odel c lass . .. s o if y ou d ont c hange i t , d jangow ill t ry and c all t hat m ethod o n y our m odel c lass i nstead o f o n y our m odel ad min c lass . .. w hich w ont w ork b ecause t hereisn os uchm ethodd efinedo ny ourm odelc lass . .. anyway , h ereis howyoucoulddoit :          also note th ati hav ech angedyourfunctionnameto edi tbuttontogetedi tin k(). Becaus edjangousesmethodsstartingwithgetasaccessorsoffieldsinamodelclass..soifyoudontchangeit,,djangowilltryandcallthatmethodonyourmodelclassinsteadofonyourmodeladminclass..whichwontworkbecausehereisnosuchmethoddefinedonyourmodeldefault..anyway,,hereishowyoucoulddoit.:           also note th ati hav ech angedyourfunctionnameto edi tbuttontogetedi tin k(). Becaus edjangousesmethodsstartingwithgetasaccessorsoffieldsinamodelclass..soifyoudontchangeit,,djangowilltryandcallthatmethodonyourmodelclassinsteadofonyourmodeladminclass..whichwontworkbecausehereisnosuchmethoddefinedonyourmodeldefault..anyway,,hereishowyoucoulddoit.:            also note th ati hav ech angedyourfunctionnameto edi tbuttontogetedi tin k(). Becaus edjangousesmethodsstartingwithgetasaccessorsoffieldsinamodelclass..soifyoudontchangeit,,djangowilltryandcallthatmethodonyourmodelclassinsteadofonyourmodeladminclass.,,.anyway,,hereishowyoucoulddoit.:             also note th ati hav ech angedyou rfunct ionnametoeditt buttongetedi tin k().Becaus edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delcl assinsteadofonyourmodela mincl ass.,,.Whichwotnworkbecau seherenosuchmehoddefindeon yo urmod elcl ass.,,.Anywaayhreish owyocouldoit.:              alsonotehatihavechangedyourfunctionnametoeditt buttongetedi tin k().Becaus edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delcl assinsteadofonyourmodela mincl ass.,,.Whichwotnworkbecau seherenosuchmehoddefindeon yo urmod elcl ass.,,.Anywaayhreish owyocouldoit.:               alsonotehatihavechangedyourfunctionnametoeditt buttongetedi tin k().Becaus edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delcl assinsteadofonyourmodela mincl ass.,,.Whichwotnworkbecau seherenosuchmehoddefindeon yo urmod elcl ass.,,.Anywaayhreish owyocouldoit.:                alsonotehatihavechangedyourfunctionnametoeditt buttongetedi tin k().Becaus edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delcl assinsteadofonyourmodela minc lassthenwillnotbeabletofindthismehodinyourapplicationbecauseitsnotdefinedintheurlpatternsyourapplicationhasbeenconfiguredtousebutthiswillstillgiveyouideahoweasyitisusethebuiltinf

unctionsdjangoprovidesforyouinordertogenerateurlsinyourapplication.,,.Whichwotnworkbecau seherenosuchmehoddefindeon yo urmod elcl ass.,,.Anywaayhreish owyocouldoit.: alsonotehatihavechangedyourfunctionnametoeditt buttongetedi tin k().Becaus edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delcl assinsteadofonyourmodela minc lassthenwillnotbeabletofindthismehodinyourapplicationbecauseitsnotdefinedintheurlpatternsyourapplicationhasbeenconfiguredtousebutthiswillstillgiveyouideahoweasyitisusethebuiltinfunctionsdjangoprovidesforyouinordertogenerateurlsinyourapplication.,,.Whichwotnworkbecau seherenosuchmehoddefindeon yo urmod elcl ass.,,.Anywaayhreish owyocouldoit.: alsonotehatihavechangedyourfunctionnametoeditt buttongetedi tin k().Becaus edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delcl assinsteadofonyourmodela minc lassthenwillnotbeabletofindthismehodinyourapplicationbecauseitsnotdefinedintheurlpatternsyourapplicationhasbeenconfiguredtousebutthiswillstillgiveyouideahoweasyitisusethebuiltinfunctionsdjangoprovidesforyouinordertogenerateurlsinyourapplication.,,.Whichwotnworkbecau seherenosuchmehoddefindeon yo urmod elcl ass.,,.Anywaayhreish owyocouldoit.: alsonotehatihavechangedyourfunctionnametoeditt buttongetedi tin k().Becaus edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delcl classinstead ofony ourmodel adminclass ., .which wont work because here is no such method defined on your model class ., .anyway , here is how you could do it : also note that i have changed your function name to edit button () To get edit link (). Because django uses methods starting with get as accessors for fields in a model Class … so if You don’t change It , django Will Try And Call That Method On Your Model Class Instead Of On Your Model Admin Class … which Won’t Work Because There Is No Such Method Defined On Your Model Class … anyway , Here Is How You Could Do It : also note that i have changed your function name to edit button () To get edit link (). Because django uses methods starting with get as accessors for fields in a model Class … so if You don’t change It , django Will Try And Call That Method On Your Model Class Instead Of On Your Model Admin Class … which Won’t Work Because There Is No Such Method Defined On Your Model Class … anyway , Here Is How You Could Do It : also note that i have changed your function name to edit button () To get edit link (). Because django uses methods starting with get as accessors for fields in a model Class … so if You don’t change It , django Will Try And Call That Method On Your Model Class Instead Of On Your Model Admin Class … which Won’t Work Because There Is No Such Method Defined On Your Mode lClass . .. anyway , Here Is How You Could Do It : also note th ati hav ech angedyourfunctionnameto edi tbuttontogetedi tin k(). Becaus edjangousesmethodsstartingwithgetasaccessorsoffieldsinamodelclass..soifyoudontchangeit,,djangowilltryandcallthatmethodonyourmodelclassinsteadofonyourmodeladminclass..whichwontworkbecausehereisnosuchmethoddefinedonyourmodeldefault..anyway,,hereishowyoucoulddoit.: also note th ati hav ech angedyourfunctionnameto edi tbuttontogetedi tin k(). Becaus edjangousesmethodsstartingwithgetasaccessorsoffieldsinamodelclass..soifyoudontchangeit,,djangowilltryandcallthatmethodonyourmodelclassinsteadofonyourmodeladminclass..whichwontworkbecausehereisnosuchmethoddefinedony

How to customise Django

1.7

There is no one-size-fits-all answer to this question, as the best way to customise Django will vary depending on your specific needs. However, some tips on how to customise Django in 1.7 include:

1. Use custom templates and views

One way to customise Django is by using custom templates and views. This allows you to create your own templates and views that can be used to override or supplement the default templates and views provided by Django. This can be a great way to tailor the look and feel of your website specifically for your own needs.

2. Use custom settings files

Another way to customise Django is by using custom settings files. These files contain configuration information about your website, such as which databases should be used, which URLs should be accessed, and so on. By using a separate settings file for each environment (development, testing, production), you can easily configure Django exactly the way you want it without having to modify the default settings file.

3. Use third-party libraries and plugins

Finally, another way to customise Django is by using third-party libraries and plugins. These are pieces of software that allow you to do things that are not possible with the default functionality provided by Django itself. For example, you might use a library that provides support for data migrations or authentication mechanisms. By using third-party libraries and plugins, you can extend the functionality of Django beyond what is available out of the box

Buttons

Buttons are a common element in web applications. They allow users to interact with the application in various ways. For example, a button can be used to submit a form, log in, or exit the application.

Fields

Fields are a core component of Django. They are used to store data in a database. Fields are defined in a model class and can be accessed by name from views and other modules. Fields can also be assigned to objects using the field() function.

Related posts:

Leave a Comment