[英]Django class based generic view “CreateView” form errors handling
I am new to CBV and am trying to use the generic view CreateView
and understand it. 我是CBV的新手,正在尝试使用通用视图
CreateView
并了解它。
In models.py I have this model: 在models.py我有这个模型:
class CartConfig(models.Model):
cart_key = models.CharField(
'Chave do Carrinho', max_length=40, db_index=True
)
PAYMENT_OPTION_CHOICES = (
('cash', 'Dinheiro'),
...
)
payment_option = models.CharField(
'Opção de Pagamento', choices=PAYMENT_OPTION_CHOICES, max_length=20,
default='cash'
)
address = models.ForeignKey(Address, verbose_name='Endereço de entrega',
blank="false"
)
class Meta:
verbose_name = 'Configuração do carrinho'
verbose_name_plural = 'Configurações do carrinho'
def __str__(self):
return 'Cart configs for {}'.format(self.cart_key)
That model uses a ForeignKey
to Address
, which is also a ManyToMany
field in the User
model. 该模型使用
ForeignKey
到Address
,这也是User
模型中的ManyToMany
字段。 So, in my views.py I edited the queryset of ´adress´ field to handle only the address relationed to the current User
: 因此,在我的views.py中,我编辑了“ adress”字段的queryset以仅处理与当前
User
相关的地址:
class CartConfigView(CreateView):
model = CartConfig
template_name = 'checkout/cart_config.html'
fields = ['address','payment_option']
success_url = reverse_lazy('index')
def get_context_data(self, **kwargs):
context = super(CartConfigView, self).get_context_data(**kwargs)
context['form'].fields['address'].queryset = get_object_or_404(User, pk=self.request.user.pk).address.all()
context['form'].fields['address'].empty_label = None
return context
In my template it works fine, show the right address list and creat it as well through the post form. 在我的模板中,它可以正常工作,显示正确的地址列表并通过邮寄表格创建它。 But if the user don't select an address, it triggers the expected error
NOT NULL constraint failed: checkout_cartconfig.address_id
. 但是,如果用户未选择地址,则会触发预期的错误
NOT NULL constraint failed: checkout_cartconfig.address_id
。 The question is, should not the CreateView
handles this error? 问题是,
CreateView
是否应处理此错误? What am I doing wrong? 我究竟做错了什么? How can I do to the page refresh with the
field.errors
to show to the user the "required field" message? 如何使用
field.errors
刷新页面以向用户显示“必填字段”消息?
Your model is not set up quite correctly with blank="false"
. 使用
blank="false"
不能完全正确地设置模型。 It needs to be a boolean. 它必须是布尔值。
address = models.ForeignKey(
Address,
verbose_name='Endereço de entrega',
blank=False
)
Fun fact about Python: When resolving to a boolean, strings evaluate to true. 关于Python的有趣事实:解析为布尔值时,字符串评估为true。
>>> bool("false")
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.