I have a view function that toggles the user state (active-inactive):
def toggle_user_state(request, user_id, current_state):
user = get_object_or_404(User, pk=user_id)
user.is_active = not current_state
user.save()
return HttpResponseRedirect(reverse('cdms:user_details', kwargs={'user_id': user.id}))
If the current_state is True, it works properly by making it False. But if the current_state is False, it remains False.
I have also tried to print(not current_state), but surprisingly not False remains False!
I am not sure why do you need a current_state when you can simply toggle is_active on the user:
def toggle_user_state(request, user_id):
user = get_object_or_404(User, pk=user_id)
user.is_active = not user.is_active # take a NOT of active state here
user.save()
return HttpResponseRedirect(reverse('cdms:user_details', kwargs={'user_id': user.id}))
The current_state captured by the url is always a string. So, in your case it will be either "True" or "False".
not "True" # False
not "False" # False
One solution is this:
if current_state == "True":
user.is_active = False
elif current_state == "False":
user.is_active = True
Another solution is this:
# Define a function to the outer scope
def str_to_bool(s):
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError
# Then inside toggle_user_state do this
try:
user.is_active = not str_to_bool(current_state)
except ValueError:
# handle error here (its neither "True" or "False")
else:
# everything worked. Continue
not False will always return True
>>> not False
>>> True
not 'False' will always return False
>>> not 'False'
>>> False
reason is, any non-empty, string evaluates to boolean True
>>> if 'False':
>>> print 'False in string but not boolean False'
>>> 'False in string but not boolean False'
as a a recap string 'False' does not equal bool False
what I typically do here is write a truthy function that translates any potential intended meaning of true or false into a boolean value
def is_true(value):
if value in ['1', 1, True, 'true', 'yes', 'Yes', 'True']:
return True
return False
so now you can do
def toggle_user_state(request, user_id, current_state):
user = get_object_or_404(User, pk=user_id)
current_state = is_true(current_state) # current_state will now be boolean
user.is_active = not current_state # now, will be boolean opposite
user.save()
return HttpResponseRedirect(reverse('cdms:user_details', kwargs={'user_id': user.id}))
Related
I have the following object field:
is_vendor = models.BooleanField(default=False)
I have the following if statement:
print(customer.is_vendor) //This prints False
if customer.is_vendor:
print('im a vendor') //This prints even the value above is false
else:
print('im not a vendor')
Why is this occurring?
You have a string in the field -- "False" as opposed to False. Which is cool for Django but not python. Try customer.is_vendor.to_python() instead. That will wrangle it into a boolean for you.
if "False": print 'True!' # is True
if False: print 'True!' # Nope.
if customer.is_vendor.to_python():
print "Is a vendor!"
def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) == a%n:
return True
else:
return False
When I check n for a given value it just check 2, then decides if it is true or false and doesn't check the rest of the range. Not sure how to make it check the rest of the range.
That's because you're using a return inside the if-else block. You might want to change the return statement by a print one indicating if it is a prime number or not.
If you want it to return True if all are prime-like or False if at least one is not, then do the following:
def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) != a%n:
print('One element is false')
return False
return True
The print statement is just to show something, but it's not relevant.
I would try making a list and allow your for loop to append the results of the range into the list then return the list as a whole so you can have access to all the results.
edit: Complely missed the point of your question. Here's the edit.
import sys
def isprimelike(n):
resultlist = []
for a in range(2,int(n)-1):
if pow(a,int(n),int(n)) == a%int(n):
result.append(True)
else:
result.append(False)
return resultlist
n = sys.argv[1]
resultlist = isprimelike(n)
if True in resultlist:
if False in resultlist:
print('List contains both True and False')
sys.exit(1)
else:
print('List is all True')
sys.exit(1)
if False in resultlist:
if True in resultlist:
print('List contains both True and False')
else:
print('List is all False')
In Django, I have a ChoiceField that looks like this:
completed = forms.ChoiceField(choices = COMPLETED_CHOICES, required = True)
Here's the COMPLETED_CHOICES:
COMPLETED_CHOICES = (
('', ''),
(True, "Yes"),
(False, "No")
)
This is my model.py:
completed = models.BooleanField(choices = COMPLETED_CHOICES)
My problem is that every time I make a new instance, if I chose "No" on the form, the value will be saved as True. Meanwhile, if I chose "Yes", it'll save as True, which works as expected. Why is "No" only being affected?
Here's the relevant part of views.py
completed = form.cleaned_data['completed']
book = Book(
completed = completed,
)
book.save()
Your False value is probably passed from a form as a string. Take a look at the following code:
>>>print False
False
>>>
>>>print "False"
False
>>>
>>>
>>>if False:
... print 1
>>>
>>>if "False":
... print 1
1
Then you will need to parse the value from string by using for example
completed = form.cleaned_data['completed'] == 'True'
You can always check the type of given value by using type( form.cleaned_data['completed'] )
I'm trying to make a very simple regex match ( the negation of all printable anscii characters other then '[' and ']'). When I tested my pattern in regex pal I got the matching that I wanted. Then I moved to my python unit test and my match never returns true
def testChatChars(string):
return re.match('[^\x20-\x5A\x5C\x5E-\x7E]', string) is not None
print("testing Chat validation")
print(testChatChars("") == False)
print(testChatChars("this is a valid chat message") == True)
print(testChatChars("9999abcdefghijklmnopqrxtuvxyz ABCDEFGHIJKLMNOP!##$(^&*(&%$^^)*)!{},.;'\|?/7") == True )
print(testChatChars("this is not [ valid chat message") == False)
print(testChatChars("this is not ] valid chat message") == False)
print(testChatChars("9999abcdefghijklmnopqrxtuvxyz [][][[][]ABCDEFGHIJKLMNOP!##$(^&*(&%$^^)*)!{}[],.;'\|?/7ونِكود碼標準萬國") == False)
Which is returning
False //should be true
False //should be true
False //should be true
True
True
True
re.match is always returning none for some reason.
UPDATE:
tried to change my code in the suggested fashion
new output is
False
False
True
False
False
False
def testChatChars(string):
return re.match(r'[\x20-\x5A\x5C\x5E-\x7E]+$', string) is not None
i wish to use a statement "True" and "False" for my Python (2.7) command prompt
segmentation_accuracy(reference=REFERENCE, segmented=SEGMENTED, output=OUTPUT, method=METHOD, threshold=THRESHOLD, sep=SEP, header=HEADER)
if header is True print a text file with an header, if header is False print a text file without an header.
in Command Prompt:
REFERENCE = raw_input("Reference (*.shp):")
SEGMENTED = raw_input("Segmented (*.shp):")
METHOD = raw_input("Method (ke, pu, clinton):")
if METHOD != "ke" and METHOD != "pu" and METHOD != "clinton":
raise ValueError("%s is not a valid method" % METHOD)
if METHOD == "ke" or METHOD == "clinton":
THRESHOLD = input("Threshold (0.0 - 1.0):")
if not check_threshold(THRESHOLD):
raise AccuracyException("Threshold of %s is not valid" % THRESHOLD)
else:
THRESHOLD = None
SEP = raw_input("Sep:")
HEADER = raw_input("Header (True/False):")
if HEADER is not True or HEADER is not False:
raise ValueError("%s is not valid" % HEADER)
# output
OUTPUT = raw_input("Output (*.txt):")
when i run the command prompt in windows if i set raw_input("Header (True/False):") True or False, I always get the ValueError
i also used the combination
if HEADER != True or HEADER != False:
raise ValueError("%s is not valid" % HEADER)
with the same problem
The return value from raw_input is a string and not a boolean. Hence your is not True and is not False tests, although they have well-defined meaning, that meaning is not the meaning that you intend. You need to compare HEADER against string values.
So you would need, for example, code like this:
if HEADER.lower() == 'true':
I used tolower() to effect case-insensitive comparison. You may also want to strip off white space:
if HEADER.strip().lower() == 'true':
I'm sure you can fill in the test against false yourself.
Even if you did have a boolean, you should not use code like is not True or is False. You should test for truth with:
if somebool:
or
if not somebool:
because it is much more readable.
HEADER is a string, not a boolean. This will cause the is check to fail. Your comparison runs like this:
>>> "True" is not True
True
>>> "True" is not False
True
Note that a comparison with == will also fail:
>>> "True" == True
False
>>> "True" == False
False
Try comparing the value as a string:
if HEADER.tolower() == 'true':
#do something
elif HEADER.tolower() == 'false:
#do something else