gpt4 book ai didi

Django admin - 通过内联自动将当前用户保存到模型?

转载 作者:行者123 更新时间:2023-12-04 14:25:12 25 4
gpt4 key购买 nike

我有以下内容,当我尝试通过管理页面上传文档以进行处理时,它会抛出错误。使用内联时如何自动填充文档模型的 entered_by 字段?

错误:/admin/myapp/proceeding/6/change/处出现 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()

最佳答案

example in the docs save_formset 展示了如何做到这一点。使用 commit=False 保存表单集,然后遍历实例并将 entered_by 字段设置为 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 方法,因为它没有任何内联。

关于Django admin - 通过内联自动将当前用户保存到模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com