如何在 Django 中设置布尔值 [英] How can set the boolean value in django

查看:70
本文介绍了如何在 Django 中设置布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在选择复选框时设置布尔值 True,但当我选择它时显示错误

I am trying to get set the boolean value True when the checkbox is selected but when i select it show the error

    failed["">" value must be either True or False."]

当我设置密码对象没有条带功能时它也显示错误

and also it show the error when i set the password object have no strip fucntion

模型/py

 from django.db import models
 from django.contrib.auth.models import AbstractUser

 class Auth_User(AbstractUser):
    is_vendor = models.BooleanField(default=False)

查看.py

class Sign_up(TemplateView):
   template_name = 'Sign-up.html'

   def get(self, request, *args, **kwargs):
        return render(request, self.template_name)

   def post(self, request):
        try:
           data = self.request.POST.get
           user = Auth_User(
               username=data,
               email=data,
               is_vendor=data
           )
           user.set_password(data('password').strip())
           user.save()
           return render(request, 'home.html')
        except Exception as e:
           return HttpResponse('failed{}'.format(e))

HTML

 <label for="is_vendor">is_vendor
        <input type="checkbox" name="is_vendor">
    </label><br>

推荐答案

假设您没有在此视图上使用 Form 类,您的代码应如下所示:

Assuming you are not using a Form class on this view, your code should look like this:

def post(self, request):
    data = self.request.POST
    user = Auth_User(
        username=data.get('username'),
        email=data.get('email'),
        is_vendor=data.get('is_vender'),
    )
    user.set_password(data.get('password'))
    user.save()
    return render(request, 'home.html')

如果字段是必需的,您将需要检查每个输入的值.或者您使用 Form 类在后期为您执行此操作.请参阅 https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-editing/ 了解更多信息.

If the fields are required, you will need to check the values for each input. Or you use a Form class that does this for you in post. See https://docs.djangoproject.com/en/3.2/topics/class-based-views/generic-editing/ for more info.

这篇关于如何在 Django 中设置布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆