我的模板中有一个表单包含两个复选框。如果用户未选中复选框,则POST对象中没有任何内容。如果用户检查它,则request.POST.get(" check1")返回空字符串。当我创建对象并填充布尔字段时,由于空字符串,它变为False。
class NewCustomer(View):
def get(self, request):
c = {}
c.update(csrf(request))
return render_to_response("Customer/NewCustomer.html", c)
def post(self, request):
customer = Customer.create(request.POST.get("name", ""), request.POST.get("surname", ""),
request.POST.get("phoneNumber", ""), request.POST.get("address", ""),
request.POST.get("sendSms", ""), request.POST.get("sendEmail", False),
request.POST.get("email", False))
return redirect("GetCustomer", customerId=customer.id)
sendSms和sendEmail是复选框。
class Customer(models.Model):
Name = models.TextField(blank=False)
Surname = models.TextField(blank=False)
PhoneNumber = models.TextField()
Address = models.TextField()
SendSms = models.BooleanField(default=True)
SendEmail = models.BooleanField(default=True)
Email = models.TextField()
Created = models.DateField(auto_now_add=True)
@classmethod
def create(cls, name, surname, phoneNumber, address , sendSms, sendEmail, email):
customer = cls(Name=name, Surname=surname, PhoneNumber=phoneNumber
, Address=address, SendSms=sendSms, SendEmail=sendEmail
, Email=email)
customer.save()
return customer
读取复选框并为我的布尔字段赋值的正确方法是什么?
答案 0 :(得分:2)
尝试
is_checked = "check1" in request.POST