gpt4 book ai didi

django - 有没有办法在 Django 内联表单集清理方法中访问请求对象?

转载 作者:行者123 更新时间:2023-12-02 15:00:21 26 4
gpt4 key购买 nike

得到这个带有内联和表单类的管理类:

class InvoiceAdmin(admin.ModelAdmin):
....
inlines = [InvoiceLineInline, ]
form = InvoiceForm
....

class InvoiceForm(forms.ModelForm):
....
def clean():
....

class Meta:
model = Invoice
exclude = []


class InvoiceLineInline(admin.TabularInline):
model = InvoiceLine
formset = InvoiceLineInlineFormset
extra = 1


class InvoiceLineInlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
super(InvoiceLineInlineFormset, self).clean()

count = 0
for form in self.forms:
if not hasattr(form, 'cleaned_data'):
continue

data = form.cleaned_data
try:
if data:
count += 1
else:
continue
except AttributeError:
pass

if Decimal(data.get('quantity', 0)) <= 0:
raise forms.ValidationError("Amount should be greater than 0.")
******************************************************
_stock_code = data.get('stock_code', None)
if not len(fetch_stocks_from_connector(request, stock_code=_stock_code)):
raise forms.ValidationError("{} Stock code does not exist at connector.".format(_stock_code))
******************************************************
if count < 1:
raise forms.ValidationError('Need one line at least.')

我需要使用外部方法对 InvoiceLineInlineFormset.clean 中每个 inlineform 中的 _stock_code 值进行额外验证,如上图所示加星标的线。但是外部方法需要请求对象作为参数才能正常运行。

是否可以将请求对象传递给 clean 方法?

最佳答案

问题很老,但我会分享对我有用的解决方案ModelAdmin 有一个 get_formset 方法。你可以像这样扩展它

class YourAdminInline(admin.TabularInline):
model = YourModel
formset = YourInlineFormSet

def get_formset(self,request,obj=None,**kwargs):
formset = super(YourAdminInline,self).get_formset(request,obj,**kwargs)
formset.request = request
return formset

在您的表单集中,您可以使用 self.request 访问请求对象。比如在clean方法中

class YourInlineFormset(forms.BaseInlineFormset):
def clean(self):
...
request = self.request

关于django - 有没有办法在 Django 内联表单集清理方法中访问请求对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50236593/

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