Django Admin에서 필드 크기 조정
Django는 관리자에서 항목을 추가하거나 편집 할 때 가로 공간을 채우는 경향이 있지만, 경우에 따라 날짜 필드, 8 자 너비 또는 CharField, 6 또는 8을 편집 할 때 공간 낭비가됩니다. 문자가 넓고 편집 상자는 최대 15 자 또는 20 자까지 표시됩니다.
관리자에게 텍스트 상자의 너비 또는 텍스트 필드 편집 상자의 높이를 어떻게 알릴 수 있습니까?
ModelAdmin.formfield_overrides를 사용해야합니다 .
매우 쉽습니다-에서 admin.py
정의하십시오.
from django.forms import TextInput, Textarea
from django.db import models
class YourModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size':'20'})},
models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':40})},
}
admin.site.register(YourModel, YourModelAdmin)
"attrs"속성을 사용하여 위젯에 임의의 HTML 속성을 설정할 수 있습니다 .
Django 관리자에서 formfield_for_dbfield를 사용하여이 작업을 수행 할 수 있습니다.
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
field = super(ContentAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'somefield':
field.widget.attrs['class'] = 'someclass ' + field.widget.attrs.get('class', '')
return field
또는 사용자 정의 위젯 하위 클래스 및 formfield_overrides 사전 과 함께 :
class DifferentlySizedTextarea(forms.Textarea):
def __init__(self, *args, **kwargs):
attrs = kwargs.setdefault('attrs', {})
attrs.setdefault('cols', 80)
attrs.setdefault('rows', 5)
super(DifferentlySizedTextarea, self).__init__(*args, **kwargs)
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = { models.TextField: {'widget': DifferentlySizedTextarea}}
특정 필드의 너비를 변경하려면.
ModelAdmin.get_form을 통해 작성 :
class YourModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(YourModelAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['myfield'].widget.attrs['style'] = 'width: 45em;'
return form
빠르고 더러운 옵션은 해당 모델에 대한 사용자 지정 템플릿을 제공하는 것입니다.
이름이 지정된 템플릿을 생성 admin/<app label>/<class name>/change_form.html
하면 관리자는 기본값 대신 해당 템플릿을 사용합니다. 즉, 이름이라는 Person
앱에 이름이 지정된 모델이있는 경우 라는 people
템플릿을 만듭니다 admin/people/person/change_form.html
.
모든 관리 템플릿에는에 항목 extrahead
을 배치하기 위해 재정의 할 수 있는 블록이 있으며 <head>
퍼즐의 마지막 부분은 모든 필드에 HTML ID가 id_<field-name>
.
따라서 템플릿에 다음과 같은 내용을 넣을 수 있습니다.
{% extends "admin/change_form.html" %}
{% block extrahead %}
{{ block.super }}
<style type="text/css">
#id_my_field { width: 100px; }
</style>
{% endblock %}
필드 별 인스턴스의 속성을 변경하려는 경우 "attrs"속성을 양식 항목에 직접 추가 할 수 있습니다.
예를 들면 :
class BlogPostForm(forms.ModelForm):
title = forms.CharField(label='Title:', max_length=128)
body = forms.CharField(label='Post:', max_length=2000,
widget=forms.Textarea(attrs={'rows':'5', 'cols': '5'}))
class Meta:
model = BlogPost
fields = ('title', 'body')
The "attrs" property basically passes along the HTML markup that will adjust the form field. Each entry is a tuple of the attribute you would like to override and the value you would like to override it with. You can enter as many attributes as you like as long as you separate each tuple with a comma.
The best way I found is something like this:
class NotificationForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(NotificationForm, self).__init__(*args, **kwargs)
self.fields['content'].widget.attrs['cols'] = 80
self.fields['content'].widget.attrs['rows'] = 15
self.fields['title'].widget.attrs['size'] = 50
class Meta:
model = Notification
Its much better for ModelForm than overriding fields with different widgets, as it preserves name
and help_text
attributes and also default values of model fields, so you don't have to copy them to your form.
I had a similar problem with TextField. I'm using Django 1.0.2 and wanted to change the default value for 'rows' in the associated textarea. formfield_overrides doesn't exist in this version. Overriding formfield_for_dbfield worked but I had to do it for each of my ModelAdmin subclasses or it would result in a recursion error. Eventually, I found that adding the code below to models.py works:
from django.forms import Textarea
class MyTextField(models.TextField):
#A more reasonably sized textarea
def formfield(self, **kwargs):
kwargs.update(
{"widget": Textarea(attrs={'rows':2, 'cols':80})}
)
return super(MyTextField, self).formfield(**kwargs)
Then use MyTextField instead of TextField when defining your models. I adapted it from this answer to a similar question.
It's well described in Django FAQ:
Q: How do I change the attributes for a widget on a field in my model?
A: Override the formfield_for_dbfield in the ModelAdmin/StackedInline/TabularInline class
class MyOtherModelInline(admin.StackedInline):
model = MyOtherModel
extra = 1
def formfield_for_dbfield(self, db_field, **kwargs):
# This method will turn all TextFields into giant TextFields
if isinstance(db_field, models.TextField):
return forms.CharField(widget=forms.Textarea(attrs={'cols': 130, 'rows':30, 'class': 'docx'}))
return super(MyOtherModelInline, self).formfield_for_dbfield(db_field, **kwargs)
You can always set your fields sizes in a custom stylesheet and tell Django to use that for your ModelAdmin class:
class MyModelAdmin(ModelAdmin):
class Media:
css = {"all": ("my_stylesheet.css",)}
for 1.6, using forms I had to specify the attributes of the textarea inside the charfield:
test1 = forms.CharField(max_length=400, widget=forms.Textarea( attrs={'rows':'2', 'cols': '10'}), initial='', help_text=helptexts.helptxt['test'])
Same answer as msdin but with TextInput instead of TextArea:
from django.forms import TextInput
class ShortTextField(models.TextField):
def formfield(self, **kwargs):
kwargs.update(
{"widget": TextInput(attrs={'size': 10})}
)
return super(ShortTextField, self).formfield(**kwargs)
Here is a simple, yet flexible solution. Use a custom form to override some widgets.
# models.py
class Elephant(models.Model):
name = models.CharField(max_length=25)
age = models.IntegerField()
# forms.py
class ElephantForm(forms.ModelForm):
class Meta:
widgets = {
'age': forms.TextInput(attrs={'size': 3}),
}
# admin.py
@admin.register(Elephant)
class ElephantAdmin(admin.ModelAdmin):
form = ElephantForm
The widgets given in ElephantForm
will replace the default ones. The key is the string representation of the field. Fields not specified in the form will use the default widget.
Note that although age
is an IntegerField
we can use the TextInput
widget, because unlike the NumberInput
, TextInput
accepts the size
attribute.
This solution is described in this article.
If you are working with a ForeignKey field that involves choices/options/a dropdown menu, you can override formfield_for_foreignkey
in the Admin instance:
class YourNewAdmin(admin.ModelAdmin):
...
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'your_fk_field':
""" For your FK field of choice, override the dropdown style """
kwargs["widget"] = django.forms.widgets.Select(attrs={
'style': 'width: 250px;'
})
return super().formfield_for_foreignkey(db_field, request, **kwargs)
More information on this pattern here and here.
And one more example too :
class SecenekInline(admin.TabularInline):
model = Secenek
# classes = ['collapse']
def formfield_for_dbfield(self, db_field, **kwargs):
field = super(SecenekInline, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'harf':
field.widget = TextInput(attrs={'size':2})
return field
formfield_overrides = {
models.TextField: {'widget': Textarea(attrs={'rows':2})},
}
extra = 2
If you want to edit only a specific fields size, you can use this.
참고URL : https://stackoverflow.com/questions/910169/resize-fields-in-django-admin
'Programing' 카테고리의 다른 글
SQL Server가 '잘못된 열 이름'을보고하지만 열이 있고 쿼리가 Management Studio를 통해 작동합니다. (0) | 2020.08.15 |
---|---|
vim이 파일을 html로 구문 강조하도록 강제하는 방법은 무엇입니까? (0) | 2020.08.15 |
NSString의 처음 세 문자를 얻는 방법? (0) | 2020.08.15 |
페이지를 다시로드하지 않는 HTML 버튼을 만드는 방법 (0) | 2020.08.15 |
CSS3 변환이 작동하지 않음 (0) | 2020.08.15 |