许多玩具具有相同的信息(例如描述和价格)我如何自定义我的admin.py以获取最后保存的对象值,每次当我在管理面板中添加新玩具并在我的输入字段中显示它们时。
models.py
TransformPattern pattern = (TransformPattern)element.GetCurrentPattern(TransformPattern.Pattern);
if (pattern.Current.CanResize)
{
pattern.Resize(700, 700);
}
admin.py
class Toy(models.Model):
name = models.CharField(max_length=255)
description = TextField()
quantity = models.FloatField(default=0.0)
price = models.FloatField()
def __unicode__(self):
return self.name
答案 0 :(得分:1)
尝试这样做:
首先在admin.py
中创建一个表单:
class ToyForm(forms.ModelForm):
class Meta:
model = Toy
fields = ('__all__')
def __init__(self, *args, **kwargs):
#if not an edit
if 'instance' not in kwargs:
#we get the last object
last_object = Toy.objects.all().order_by("id")[0]
#we add the last object informations to the initial data
initial = {'description': last_object.description, 'price': last_object.price}
kwargs['initial'] = initial
super(ToyForm, self).__init__(*args, **kwargs)
然后将此表单添加到Admin模型:
class ToyAdmin(admin.ModelAdmin):
form = ToyForm
Fianally:
admin.site.register(ToyAdmin, Toy)
答案 1 :(得分:0)
在modeladmin类中有一个方法get_form,你可以覆盖要返回的方法,从条件查询集结果返回的值(Mymodel.objects.last())
from django.contrib import admin
@admin.register(Toy)
class ToyAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(ToyAdmin, self).get_form(request, obj, **kwargs)
# code logic to check condition & queryset like Toy.objects.last()
form.base_fields['name'].initial = 'value'
return form