해결됨: 필드에서 django 관리자 편집 모델 버튼 사용자 정의

마지막 업데이트 : 09/11/2023

주요 문제는 필드에서 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 '&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 seherenosmehoddefindeon yo urmod elcl ass.,,.Anywaayhreish owycouldoit.: alsonotehatihavechangedyourfunctionnametoeditt buttongetedi tin k().Because edjanganusesmetho dswithstartin gwithgeasacces sorforfie lsinamodelelass.,,.Soifdondtchan geittryan calllhatmet ho donyourmo delclyour assthenanotbeon대신모델 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 에는 그러한 방법이 정의되어 있지 않습니다. .. 어쨌든, 여기 당신이 그것을 할 수 있는 방법이 있습니다: 또한 ati가 당신의 함수 이름을 편집하기 위해 버튼을 사용하여 k()를 얻었음을 주목하십시오. 왜냐면 edjangouses 메소드는 모델 클래스의 접근자로서 get으로 시작하므로 변경하지 않으면 django는 모델 관리 클래스 대신 모델 클래스에서 해당 메소드를 호출할 것입니다. 이는 작동하지 않을 것입니다. 여기서는 모델 기본값에 정의된 그러한 메소드가 없기 때문입니다. 어쨌든 여기에서 수행할 수 있습니다. edjango는 모델 클래스의 필드 접근자로 get을 사용하는 메서드를 사용하기 때문에 변경하지 않으면 django는 모델 관리자 클래스 대신 모델 클래스에서 해당 메서드를 호출하려고 시도하지만, 정의된 메서드가 없으므로 작동하지 않습니다.

장고를 커스터마이즈하는 방법

1.7

Django를 사용자 지정하는 가장 좋은 방법은 특정 요구 사항에 따라 다르기 때문에 이 질문에 대한 일률적인 대답은 없습니다. 그러나 1.7에서 Django를 사용자 지정하는 방법에 대한 몇 가지 팁은 다음과 같습니다.

1. 사용자 지정 템플릿 및 보기 사용

Django를 사용자 지정하는 한 가지 방법은 사용자 지정 템플릿과 보기를 사용하는 것입니다. 이를 통해 Django에서 제공하는 기본 템플릿 및 보기를 재정의하거나 보완하는 데 사용할 수 있는 고유한 템플릿 및 보기를 만들 수 있습니다. 이는 자신의 필요에 맞게 웹사이트의 모양과 느낌을 맞춤화하는 좋은 방법이 될 수 있습니다.

2. 사용자 정의 설정 파일 사용

Django를 사용자 지정하는 또 다른 방법은 사용자 지정 설정 파일을 사용하는 것입니다. 이 파일에는 사용해야 하는 데이터베이스, 액세스해야 하는 URL 등과 같은 웹 사이트에 대한 구성 정보가 포함되어 있습니다. 각 환경(개발, 테스트, 프로덕션)에 대해 별도의 설정 파일을 사용하면 기본 설정 파일을 수정하지 않고도 Django를 원하는 대로 정확하게 구성할 수 있습니다.

3. 타사 라이브러리 및 플러그인 사용

마지막으로 Django를 사용자 지정하는 또 다른 방법은 타사 라이브러리 및 플러그인을 사용하는 것입니다. 이들은 Django 자체에서 제공하는 기본 기능으로는 불가능한 일을 할 수 있게 해주는 소프트웨어입니다. 예를 들어 데이터 마이그레이션 또는 인증 메커니즘을 지원하는 라이브러리를 사용할 수 있습니다. 타사 라이브러리 및 플러그인을 사용하여 Django의 기능을 즉시 사용할 수 있는 것 이상으로 확장할 수 있습니다.

버튼

버튼은 웹 애플리케이션의 공통 요소입니다. 이를 통해 사용자는 다양한 방식으로 애플리케이션과 상호 작용할 수 있습니다. 예를 들어 버튼을 사용하여 양식을 제출하거나 로그인하거나 애플리케이션을 종료할 수 있습니다.

Fields

필드는 Django의 핵심 구성 요소입니다. 데이터베이스에 데이터를 저장하는 데 사용됩니다. 필드는 모델 클래스에서 정의되며 보기 및 기타 모듈에서 이름으로 액세스할 수 있습니다. field() 함수를 사용하여 객체에 필드를 할당할 수도 있습니다.

관련 게시물: