我有两种模式,一个是主讲人,另一个是相关的斜体。 可以说,该图形可用于对模型进行说明,并且应当跟踪在行政管理用户进行变革时的滞后情况。 虽然这似乎很简单(实际上,在用户领域是主要模型的一部分时,该数字说明了这一点),但当外地在网上时,我似乎无法抓住这个例子。
我的目标是:
- User edits MainModel
- User adds an InlineModel, not filling in the user field
- User presses save
- Code fills in the user field for newly created InlineModel instances
- (Bonus! user field is readonly for existing instances and hidden for new inlines)
我的问题:
- Is this correct? Its too bas save_model isn t called for InlineModelAdmin instances
- Does doing it this way allow me to save without causing an error? (user is required, validation flags it)
- How can I hide the user input field for new inlines, and have it readonly for existing inlines?
我目前的想法如下:
#models.py
class MainModel(models.Model):
some_info = models.IntegerField()
class InlineModel(models.Model):
main = models.ForeignKey(MainModel)
data = models.CharField(max_length=255)
user = models.ForeignKey( auth.User )
#admin.py
class InlineModelInline(admin.TabularInline):
model = InlineModel
fields = ( data , user )
#readonly_fields = ( data , user ) #Bonus question later
class MainModelAdmin(admin.ModelAdmin):
list_display = ( id , some_info )
inlines = [InlineModelInline]
#def save_model(self, request, obj, form, change):
#http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
#Only called for MainModel, not for any of the inlines
#Otherwise, would be ideal
def save_formset(self, request, form, formset, change):
#http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset
#Experimenting showd this is called once per formset (where the formset is a group of inlines)
#See code block at http://code.djangoproject.com/browser/django/tags/releases/1.2.1/django/contrib/admin/options.py#L894
if not isinstance(formset.model, InlineModel):
return super(MainModelAdmin, self).save_formset(request, form, formset, change)
instances = formset.save(commit=False)
for instance in instances:
if not instance.pk:
instance.user = request.user
instance.save()
formset.save_m2m()