简体   繁体   English

在 django/python 中,什么不是 None 代表?

[英]What does is not None stands for in django/python?

I want to display a not valid message when my html form field is empty.当我的 html 表单字段为空时,我想显示无效消息。 But the code below triggers the "if block" when the field is empty and the "else block" when the field is not empty.但是下面的代码在字段为空时触发“if 块”,当字段不为空时触发“else 块”。

I wrote it this way because this seems to do the job.我这样写是因为这似乎可以完成工作。 But I'm confused.但我很困惑。 Shouldn't it be the other way around?不应该反过来吗?

if(request.POST['amount'] is not None):

   os.remove(os.path.join(settings.MEDIA_ROOT,str(uploaded_file.name) ))
            messages.success(request,('Invalid Field....'))
            return redirect('assignFine')
else:
   form = Fine(amount=request.POST['amount'],numberPlate=num,policeUsername=request.user)
            form.save()

This condition:这个条件:

if request.POST['amount'] is not None:

Means: if the parameter exists (is not None ), do the block below, otherwise do the else part.意思是:如果参数存在不是None ),则执行下面的块,否则执行else部分。 For this to make sense, if the amount exists we should create a Fine , otherwise we signal an error.为此,如果amount存在,我们应该创建一个Fine ,否则我们会发出错误信号。 Your conditions appear to be switched!你的条件似乎被转换了!

Depending on the expected values of the amount parameter, I'd also consider using this version:根据amount参数的预期值,我也会考虑使用这个版本:

if request.POST['amount']:
  # create fine
else:
  # signal an error

It's shorter, and means: if the amount is not None , or '' , or False , or 0 or any other falsey values in Python, do the block below, otherwise do the else part.它更短,意味着:如果amount不是None ,或'' ,或False ,或0或 Python 中的任何其他 falsey 值,请执行下面的块,否则执行else部分。

You can use the phrase below to check if amount parameter exists in request.POST :您可以使用下面的短语来检查request.POST是否存在amount参数:

if 'amount' in request.POST:
    # Your code
else:
    # Else case

You can use not in operator to have negative if/else phrase:您可以使用not in运算符来获得否定的 if/else 短语:

if 'amount' not in request.POST:
    # No 'amount' available
else:
    # There is 'amount' parameter

[Edit] [编辑]

And to check if the value is not empty , False , or None you can check it in this way:并检查该值是否不为emptyFalseNone您可以通过以下方式检查它:

if 'amount' in request.POST and request.POST['amount']:
    # 'amount' exists, and is not 'empty', 'False', or 'None'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM