gpt4 book ai didi

django - 如何在 Django 中使用 unique_together 字段验证 ModelForm?

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

如何验证 unique_together 错误以及如何通过 view.py 将自定义错误消息返回到 html。请帮忙。

模型.py:

class Pcq(models.Model):
product = models.ForeignKey(Product, null=False)
component = models.ForeignKey(Component, null=False)
quantity = models.IntegerField('Quantity', null=False)

class Meta:
unique_together = ("product", "component")

def __unicode__(self):
return self.product.productname

Form.py

class PcqForm(ModelForm):
class Meta:
model = Pcq
fields = ['component', 'quantity']
exclude = ['product']

Views.py

def pcq_add(request, product_id):
if request.method == 'POST':
form = PcqForm(request.POST or None)
if form.is_valid():
pcq = form.save(commit=False)
pcq.product_id = product_id
pcq.save()
form = PcqForm()
successmsg = "Component added successfully! Add another Component..."
return render(request, 'maps/pcq/pcq_add.html', {'form': form, 'product_id': product_id, 'successmsg': successmsg})
form = PcqForm()
return render(request, 'maps/pcq/pcq_add.html', {'form': form, 'product_id': product_id})

最佳答案

您需要为表单提供自定义清理功能

class PcqForm(ModelForm):
class Meta:
model = Pcq
fields = ['component', 'quantity']
exclude = ['product']

def clean(self):
cleaned_data = super(PcqForm, self).clean()
component = cleaned_data.get('component')
quantity = cleaned_data.get('quantity')

if component and quantity:
try:
Pcq.objects.get(
component=component,
quantity=quantity,
)
except Pcq.DoesNotExist:
# Yay
pass
else
raise forms.ValidationError(_("Error message goes here"))

更新

与上面相同的概念,但在 View 中。

def pcq_add(request, product_id):
if request.method == 'POST':
form = PcqForm(request.POST or None)
data = {
'form': form,
'product_id': product_id
}
if form.is_valid():
pcq = form.save(commit=False)
pcq.product_id = product_id

try:
pcq.save()
except IntegrityError:
# You'll need to check the exception that is raised
# Handle failed unique_together
pass
else:
form = PcqForm()
data['successmsg'] = (
"Component added successfully! Add another Component.")
else:
form = PcqForm()
data = {'form': form, 'product_id': product_id}
return render(request, 'maps/pcq/pcq_add.html', data)

或者:

  • 删除排除 = ['产品']
  • GET上将product_id传递给表单form = PcqForm(initial_data={'product':product_id})
  • 使用表单验证unique_together(不确定您是否需要自定义clean)

关于django - 如何在 Django 中使用 unique_together 字段验证 ModelForm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23113889/

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