主な問題は、フィールドで django admin 編集モデル ボタンをカスタマイズすると、予期しない動作が発生する可能性があることです。
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 '<a href="/myapp/mymodel/%s">edit</a>' % 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 edjangan は、geasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhat met he dont your mo delcl ass. 代わりにbletofindthismehodinyourapplicationbecauseitsnotdefinedintheurlpatternsyourapplicationhasbeenconfiguredtousebutthiswillstillgiveyouideahoweasyitisusethebuiltinfunctionsdjangoprovidesforyouinordertogenerateurlsinyourapplication.,,.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ここではモデルクラスで定義されたそのようなメソッドがないため、機能しません., . とにかく、これを行う方法は次のとおりです: また、関数名を編集ボタン () に変更して、編集リンク () を取得することに注意してください。 django は get で始まるメソッドをモデル クラスのフィールドのアクセサーとして使用するため、それを変更しないと、django はモデル管理クラスではなくモデル クラスでそのメソッドを呼び出そうとしますが、これは機能しません。モデルクラスにそのようなメソッドは定義されていません...とにかく、これを行う方法は次のとおりです:また、関数名を編集ボタン()に変更して、編集リンク()を取得することに注意してください。 django は get で始まるメソッドをモデル クラスのフィールドのアクセサーとして使用するため、それを変更しないと、django はモデル管理クラスではなくモデル クラスでそのメソッドを呼び出そうとしますが、これは機能しません。モデルクラスにそのようなメソッドは定義されていません...とにかく、これを行う方法は次のとおりです:また、関数名を編集ボタン()に変更して、編集リンク()を取得することに注意してください。 django は get で始まるメソッドをモデル クラスのフィールドのアクセサーとして使用するため、それを変更しないと、django はモデル管理クラスではなくモデル クラスでそのメソッドを呼び出そうとしますが、これは機能しません。モード lClass で定義されたそのようなメソッドはありません。 .. とにかく、これはあなたがそれを行うことができる方法です: また、あなたの関数名を編集ボタンに変更して、k() を編集したことにも注意してください。 edjango はモデル クラスのフィールドのアクセサとして get で始まるメソッドを使用するため、それを変更しない場合、django はモデル管理クラスではなくモデル クラスでそのメソッドを呼び出しようとしますが、これは機能しません。 edjango はモデルクラスのフィールドのアクセサーとして get で始まるメソッドを使用するため、これを変更しないと、django はモデル管理クラスではなくモデルクラスでそのメソッドを呼び出そうとしますが、ここではそのようなメソッドは定義されていないため機能しません。
Django のカスタマイズ方法
1.7
Django をカスタマイズする最善の方法は、特定のニーズによって異なるため、この質問に対する万能の答えはありません。 ただし、1.7 で Django をカスタマイズする方法に関するいくつかのヒントは次のとおりです。
1. カスタム テンプレートとビューを使用する
Django をカスタマイズする XNUMX つの方法は、カスタム テンプレートとビューを使用することです。 これにより、Django が提供するデフォルトのテンプレートとビューをオーバーライドまたは補足するために使用できる独自のテンプレートとビューを作成できます。 これは、Web サイトのルック アンド フィールを独自のニーズに合わせて調整する優れた方法です。
2. カスタム設定ファイルを使用する
Django をカスタマイズするもう XNUMX つの方法は、カスタム設定ファイルを使用することです。 これらのファイルには、使用するデータベース、アクセスする URL など、Web サイトに関する構成情報が含まれています。 各環境 (開発、テスト、運用) ごとに個別の設定ファイルを使用することで、デフォルトの設定ファイルを変更することなく、Django を思いどおりに簡単に構成できます。
3.サードパーティのライブラリとプラグインを使用する
最後に、Django をカスタマイズするもう XNUMX つの方法は、サードパーティのライブラリとプラグインを使用することです。 これらは、Django 自体が提供するデフォルトの機能では不可能なことを可能にするソフトウェアです。 たとえば、データの移行や認証メカニズムをサポートするライブラリを使用できます。 サードパーティのライブラリとプラグインを使用することで、Django の機能をすぐに利用できるものを超えて拡張できます。
ボタン
ボタンは、Web アプリケーションの一般的な要素です。 これらにより、ユーザーはさまざまな方法でアプリケーションと対話できます。 たとえば、ボタンを使用してフォームを送信したり、ログインしたり、アプリケーションを終了したりできます。
フィールズ
フィールドは Django のコア コンポーネントです。 これらは、データベースにデータを格納するために使用されます。 フィールドはモデル クラスで定義され、ビューや他のモジュールから名前でアクセスできます。 field() 関数を使用して、フィールドをオブジェクトに割り当てることもできます。