简体   繁体   English

基于Django类的通用视图“ CreateView”表单错误处理

[英]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. 该模型使用ForeignKeyAddress ,这也是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.

相关问题 基于django类的通用视图“ CreateView”唯一的段错误处理 - django class based generic view “CreateView” unique slug error handeling 基于类的视图中的表单处理 - Form handling in class based view 如何将数据库查询集对象从基于类的视图(类 SignUp(generic.CreateView))传递到 Django 中的模板 - How to pass database queryset objects from class based views(class SignUp(generic.CreateView)) to templates in Django 通用 class 基于视图 CreateView - 如何将 request.user 与某个 modelobject.user 进行比较 - generic class based view CreateView - how to compare the request.user to a certain modelobject.user 使用form_class的Django CreateView未创建模型 - Django CreateView with form_class not creating model 在 Django 中手动调用基于类的通用视图 - Manually calling a class based generic view in Django 基于 Django 类的通用视图重定向 - Django class based generic view redirect 用于通用模型的Django Createview - Django Createview for generic Model Django过滤器通过用户名从基于类的通用视图中过滤通用表单Select属性,或预填充并隐藏表单Select-attribute - Django filter generic form Select attribute from generic class-based view by Username or prepopulate and hide the form Select-attribute 我将如何将此功能视图重写为 django 中的通用 CreateView - How would I rewrite this funtional view as a generic CreateView in django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM