我有以下内容,当我尝试通过管理页面上传文档时,它会抛出错误。如何在使用内联?
时自动填充Document模型的entered_by字段错误: / admin / myapp / proceeding / 6 /更改/的IntegrityError (1048,“列'entered_by_id'不能为空”)
# models.py
class Proceeding(models.model):
date = models.DateField()
entered_by = models.ForeignKey(User)
class Document(TimeStampedUserModel):
proceeding = models.ForeignKey(Proceeding)
document = models.FileField(upload_to='documents/')
entered_by = models.ForeignKey(User)
#admin.py
class DocumentAdmin(admin.ModelAdmin):
fields = ('proceeding', 'document', )
list_display = ('proceeding', 'entered_by', )
def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
instance.entered_by = request.user
instance.save()
form.save_m2m()
return instance
def save_formset(self, request, form, formset, change):
def set_user(instance):
instance.entered_by = request.user
instance.save()
if formset.model == Document:
instances = formset.save(commit=False)
map(set_user, instances)
formset.save_m2m()
return instances
else:
return formset.save()
class DocumentInline(admin.TabularInline):
model = Document
fields = (
'proceeding',
'document',
)
extra = 0
class ProceedingAdmin(admin.ModelAdmin):
inlines = [DocumentInline, ]
fields = ('date',)
list_display = ('date', 'entered_by', )
def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
instance.entered_by = request.user
instance.save()
form.save_m2m()
return instance
def save_formset(self, request, form, formset, change):
def set_user(instance):
instance.entered_by = request.user
instance.save()
if formset.model == Proceeding:
instances = formset.save(commit=False)
map(set_user, instances)
formset.save_m2m()
return instances
else:
return formset.save()
答案 0 :(得分:2)
commit=False
的{{3}}显示了如何执行此操作。使用entered_by
保存formset,然后遍历实例并将request.user
字段设置为class ProceedingAdmin(admin.ModelAdmin):
...
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
instance.entered_by = request.user
instance.save()
formset.save_m2m()
。
DocumentAdmin
请注意,您的save_formset
不需要session_name("examplecom_session");
session_set_cookie_params(0, '/', '.example.com');
session_start();
方法,因为它没有任何内联。