I am writing a script to ask user to enter a date. If it is a date format, then return the entry; otherwise, continue. But my code doesn't stop even the user input is valid. Could somebody please share some insight? Thanks!
def date_input(prompt):
while True:
date_text = raw_input(prompt)
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
return date_text
except:
print('Invalid input.')
continue
You should never use except, always check for a specific exception:
except ValueError:
Then your real error should come through. I suspect you didn't import datetime.
Related
I want to find out what content_type I'm about in my function but I'm Unable to reach the "got me" print statement no matter how I design my if statement. I also tried to use pprint to get the naming of the content_type but with no effect till now.
def mark_refunded(modeladmin, request, queryset):
queryset.update(status=2)
transactions = queryset.all()
for transaction in queryset.all():
print(transaction)
transaction.sender.acc_usd_balance += float(transaction.amount)
transaction.sender.save()
transaction.receiver.acc_usd_balance -= float(transaction.amount)
transaction.receiver.save()
print(transaction.content_type)
if transaction.content_type == "App | Sell Type A":
print("got me")
It seems that I'm unable to compare the output of print(transaction.content_type) with the if statement, why that?
I would expect that the output is the same value that I ask for at the if statement.
Assuming content_type is a foreign key, you'd need to compare if str(...) == ....
However, the more important issue here is that multiple concurrent requests will eventually absolutely surely corrupt those account balances since you're not managing them in an atomic way.
I have a integer field 'is_mobile'. Where user entering mobile. I want that when user enter wrong mobile no. format then it show warning message "invalid no. format" and also form not save without right format. For this i applied code, but it is not work as per requirement.
Code is below:
is_mobile = fields.Integer("Mobile")
#api.multi
#api.constrains('is_mobile')
def _check_phone_number(self):
for rec in self:
if rec.is_mobile and len(rec.is_mobile) != "^[0-9]{10}$" :
raise ValidationError(_("Wrong value enter"))
else:
return False
return {}
Thanks in advance
#api.onchange('mobile')
def _onchange_mobile(self):
if self.mobile:
if re.match("^[0-9]\d{10}$", self.mobile) == None:
raise ValidationError("Enter valid 10 digits Mobile number")
You can use onchange for this. don't forget to import re
If you are talking of validation then no need to add method for that in py. Just add type="tel" in xml. Like this
<input type="tel" name="phone"/>
You can refer base code and you get idea what exactly I am talking about.
I use django-gearman-commands to do some work like this document(http://pypi.python.org/pypi/django-gearman-commands/0.1) says.When I run the worker frist time ,it works well,but when I submit another job just like make a select query from DB,it can't work until I restart this worker,I found that the worker just can work well one time.
When the worker can't work well ,it still can get value which I submit,but can't go on to do the work.
I hope someone can help me .
Here is my code:
#property
def task_name(self):
return 'sync'
def do_job(self, id):
post = Post.objects.get(pk = id)
if post.photo is None and post.video is None:
try:
self.sync_text_to_facebook(post)
except :
print 'sync text error'
else:
try:
self.sync_photo_to_facebook(post)
except :
print 'sync photo error'
When I frist submit a job,it works well,and then I submit another job ,it says can't find any post.
I came across Django request.session; I know how to set and test it for a specific value.
request.session['name'] = "dummy"
and somewhere I check
if request.session['name'] == "dummy" :
#do something
But, now I have to check whether the session variable was even set in the first place? I mean how can I check whether there exists a value in the request.session['name'] is set?
Is there a way to check it?
Treat it as a Python dictionary:
if 'name' in request.session:
print request.session['name']
How to use sessions: Django documentation: How to use sessions
get will do all the work for you. Check if the key exists, if not then the value is None
if request.session.get('name', None) == "dummy":
print 'name is = dummy'
Another way of doing this is put it in try.
In this the third example code snippet
if you apply del operation in a session variable it which does not exist, so it throws KeyError.
so check it like this.
try:
print(request.session['name'])
except KeyError:
print('name variable is not set')
We use paypal on our system to check whether a user has paid before and already has an account.
This morning I received a traceback that basically gave me an integrity error.
IntegrityError: (1062, "Duplicate entry 'user_1234_before' for key 2")
My statemtent looks as follows.
try:
user = User.objects.get(email=ipn_obj.payer_email)
except:
user_slug = ("%s_%s_before") % (ipn_obj.first_name, ipn_obj.last_name)
username = slugify(user_slug)
user = User.objects.create_user(username, ipn_obj.payer_email, 'testpassword')
user.first_name = ipn_obj.first_name
user.last_name = ipn_obj.last_name
user.save()
Thanks in advance.
Never, ever use a blank except statement. What's happening here is an excellent demonstration of why.
You've presumably used that try/except block to catch the User.DoesNotExist exception. However, your code is actually raising a completely different exception. Because you're swallowing it, it's impossible to know which one, but potentially ipn_obj isn't what you think it is and doesn't have a payer_email error, so you're getting AttributeError. Or, possibly, you're getting the User.MultipleObjectReturned exception.
Change your except to except User.DoesNotExist, and then debug your actual problem.
I think you have two user with different payer_mail but same first_name and last_name: username (made up of first and last name) is the same for the two users. Probably username is a unique key on User and gives you the error.
Apart from catching the right exception (User.DoesNotExist), if you want to retain your code, I think you should 'uniquify' the username using the email field (which I suppose is unique):
user_slug = ("%s_%s_before") % (ipn_obj.first_name, ipn_obj.last_name)
with:
user_slug = ("%s_%s_%s_before") % (ipn_obj.first_name, ipn_obj.last_name, ipn_obj.payer_email)
or:
user_slug = ("%s_before") % (ipn_obj.payer_email)
The exception is actually being raised by the creation (ie INSERT statement) of a user with an already took username.
You shall check for its existence before doing this insertion .