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'] )
Related
Trying to loop through the json results from a url then print the results only if there is a change since the last result every 1 minute. Everything works except the results are just being re-written over so it always shows 'nothing changed'.
import time
import sys
import pandas as pd
def main():
result = []
print('Checking for available campsites....')
url = "https://api.reserve.albertaparks.ca/api/public/campgrounds/67/availability?campingType=campsite" \
"&arrivalDt=01-Aug-2021&departureDt=13-Sept-2021&unitSize=40&siteType=VEH"
result = pd.read_json(url)
df = pd.DataFrame.from_records(result['availability'])
df = df[df['available'] == True]
df = df[df['fcfs'] == False]
df.set_index('date', inplace=True)
print(df)
res_before = ""
while True:
res = main()
if res != res_before:
print(res)
res_before = res
else:
print("nothing changed")
# time.sleep(300)
for i in range(60):
msg = "Pausing for 1 minute"
sys.stdout.write("\r{} {} seconds ".format(msg, i))
time.sleep(1)
sys.stdout.flush()
available fcfs
date
01-Aug-2021 True False
02-Aug-2021 True False
03-Aug-2021 True False
04-Aug-2021 True False
05-Aug-2021 True False
06-Aug-2021 True False
07-Aug-2021 True False
08-Aug-2021 True False
09-Aug-2021 True False
10-Aug-2021 True False
Checking for available campsites....
None
Pausing for 1 minute 59 seconds Checking for available campsites....
nothing changed
As #Praveen noted, you didn't return anything from your function. Below is a section of code with a couple changes that make your code run correctly. See commented lines for needed changes.
df.set_index('date', inplace=True)
print(df)
return df #>>>> return dataframe
res_before = pd.DataFrame() #>>>> want to compare dataframes correctly
while True:
res = main()
if not res.equals(res_before): #>>>> want to compare dataframes correctly
print(res)
res_before = res
You did not return anything from the main() function. So, you can't assign a function as a value to a variable
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!"
So I have a function that checks to see if my favorite sports team plays that day:
def checkGameDay():
today = str(datetime.date.today())
yyyymmdd = today.replace('-', '')
#yyyymmdd = '20171104' #test date that toronto played on (lost 6-4 to stL)
url = 'http://scores.nbcsports.msnbc.com/ticker/data/gamesMSNBC.js.asp?sport=%s&period=%s'
r = requests.get(url % ('NHL', yyyymmdd))
json_parsed = r.json()
check = 0
for game_str in json_parsed.get('games', []):
game_tree = ElementTree.XML(game_str)
away_tree = game_tree.find('visiting-team')
home_tree = game_tree.find('home-team')
gamestate_tree = game_tree.find('gamestate')
home_nickname = home_tree.get('nickname')
away_nickname = away_tree.get('nickname')
home_alias = home_tree.get('alias')
away_alias = away_tree.get('alias')
away_score = away_tree.get('score')
home_score = home_tree.get('score')
x = 0;
gamesToday = len(json_parsed.get('games', []))
if away_alias == 'Tor' or home_alias == 'Tor':
checkGoal()
print "Toronto is playing today"
return True
else:
check = check + 1
if check == gamesToday:
print "Toronto does not play today"
return False
I am a novice programmer so please ignore any "good practices" or "more efficient ways" that I am missing!
If Toronto plays on that given day, True will be returned, and False when they don't. I want this value to be returned so I can use it's result later in the code although I can't figure out how to get the return of a scheduled event.
I set up the schedule using this code:
schedule.every().day.at("18:00").run(checkGameDay)
while True:
schedule.run_pending()
time.sleep(1)
I know the returns should be triggered because the prints work perfectly fine!
Anybody know how I can create a variable that takes on this returned value? Thanks so much! I am so stuck on this...
Try something like this:
bool_value = False
def test_function():
global bool_value
#bool_value = False
for i in range(10):
if i%2 == 1:
bool_value = True
else:
bool_value = False
#return bool_value
storedVariable = bool_value
Do not return any value from the function. Define the variable globally and update it for later use.
Hope this helps.
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}))
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