[英]How to access Django Model Fields from save_formset
I have an Inline Model in Django model admin, and I need to create a condition before saving the items, here is the code am using:我在 Django model 管理员中有一个内联 Model,我需要在保存项目之前创建一个条件,这是正在使用的代码:
class PRCItemInline(admin.TabularInline):
def get_form(self, request, obj=None, **kwargs):
form = super(PRCItemInline, self).get_form(request, obj, **kwargs)
form.base_fields['product'].widget.attrs['style'] = 'width: 50px;'
return form
ordering = ['id']
model = PRCItem
extra = 1
autocomplete_fields = [
'product',
'supplier',
]
fields = (
'product', # 1
'quantity', # 2
'unitary_value_reais_updated', # 4
'issuing_status',
'approval_status',
'receiving_status',
)
readonly_fields = ['issuing_status',
'approval_status',
'receiving_status',
]
def save_formset(self, request, form, formset, change):
obj = form.instance
if obj.purchase_request.is_analizer:
return HttpResponse("You can't change this")
else:
obj.save()
As you see, I used the save_formset
method to be able to reach the fields of the model, and then filter based on it.如您所见,我使用save_formset
方法能够到达model的字段,然后根据它进行过滤。 but it just saves the items no matter the If statement I added.但无论我添加的 If 语句如何,它都只会保存项目。
First thing:第一件事:
List item save_formset
should not return anything, the HttpResponse
will not work for you.列表项save_formset
不应返回任何内容, HttpResponse
将不适合您。 Even if it would this is just not proper way.即使这样,这也不是正确的方法。 Not mentioning that it will not be very informational.更不用说它不会提供很多信息。
obj.purchase_request.is_analizer
should be done during form validation obj.purchase_request.is_analizer
应该在表单验证期间完成
Any ValidationError
raised there will be propagated to the formset and displayed in error message next to relevant form.那里引发的任何ValidationError
都将传播到表单集并显示在相关表单旁边的错误消息中。
class PRCItemForm(forms.ModelForm):
def validate(self):
if obj.purchase_request.is_analizer: raise ValidationError("You can't change this")
override get_queryset()
and filter out the objects you cannot edit覆盖get_queryset()
并过滤掉您无法编辑的对象
def get_queryset(self):
qs = super().get_queryset()
return qs.exclude(purchase_request__is_analizer=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.