In my Django project, I have a models.py that looks like this:
from django.db import models
class Battle(models.Model):
def __str__(self):
return self.battle_name
battle_name = models.CharField(max_length=200)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
password = models.CharField(max_length=50)
When I drop to the Django shell (python manage.py shell), I can't interact either of the DateTimeField properties.
$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
Am I missing something?
Let me add a bit of explanation..
Battle.objects.filter(end_time < datetime.datetime.now())
here filter() is a callable that accepts arguments (args or kwargs). With the above code you are trying to pass a boolean value (object < object) to the filter callable as argument. Now, does a boolean value True or False specify anything about a model field?
What you should be doing is pass a keyword argument, namely
Battle.objects.filter(end_time__lt=datetime.datetime.now())
Now the filter() gets the info it needs, the kwarg parameter end_time__lt (which specifies the model field along with the compare method) and the value that needs to be compared with datetime.datetime.now()
You make syntax error
Try this
Battle.objects.filter(end_time__lt=datetime.datetime.now())
Related
Can't instantiate objects using python interpreter, please help.
So inside of my python file expresser.py I have something like
class Expresser:
def __init__(self):
pass
...
Now when I type in the terminal
python
and then
>>> import expresser
>>> test_object = Expresser()
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Expresser' is not defined
I'm using PyCharm
when I type where python I get three diff locations so I suspect that but don't know how to rectify
I guess you meant:
from expresser import Expresser
Or:
from expresser import *
https://security.openstack.org/guidelines/dg_using-file-paths.html
If I try to run the given code from the above link:
import os
def is_safe_path(basedir, path, follow_symlinks=True):
# resolves symbolic links
if follow_symlinks:
matchpath = os.path.realpath(path).startswith(basedir)
else:
matchpath = os.path.abspath(path).startswith(basedir)
return basedir == os.path.commonpath((basedir, matchpath))
is_safe_path('/test', '/test/../abc')
It clearly does not work:
$ python
Python 3.8.8 (default, Mar 4 2021, 21:24:42)
[GCC 10.2.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> def is_safe_path(basedir, path, follow_symlinks=True):
... # resolves symbolic links
... if follow_symlinks:
... matchpath = os.path.realpath(path).startswith(basedir)
... else:
... matchpath = os.path.abspath(path).startswith(basedir)
... return basedir == os.path.commonpath((basedir, matchpath))
...
>>> is_safe_path('/test', '/test/../abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in is_safe_path
File "/usr/lib/python3.8/posixpath.py", line 496, in commonpath
paths = tuple(map(os.fspath, paths))
TypeError: expected str, bytes or os.PathLike object, not bool
What's the spurious bit of code here?
Should the .startswith() be removed?
Am I totally misunderstanding what the purpose of having a boolean in the tuple is?
I found the edit where this was changed:
https://bugs.launchpad.net/ossa/+bug/1815422
https://review.opendev.org/c/openstack/ossa/+/771854/
This is a typo in the code, .startswith(basedir) isn't meant to follow realpath or abspath. Most likely a copy and paste issue to be honest. I would highly recommend that you submit a fix for the issue!
I am facing a problem in python. Tho the error is quite common, but since i am bit new to python, unable to comprehend the source hence asking you all. There are 2 modules: session.py and objects.py.
session.py
import copy
import pymongo
import spacy
import tweepy
import objects
objects.py:
import re
def refresh (sv = sv, obj = ''):
return 0
now, in python shell, i am getting the error before even executing objects.py:
$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import session
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "session.py", line 6, in <module>
import objects
File "objects.py", line 3, in <module>
def refresh (sv = sv, obj = ''):
NameError: name 'sv' is not defined
>>>
I came from perl background to maybe missing some very common thing, but still i am able to do this:
>>> def ff(t): print t
...
In above, whitout defining t, it is working while in objects.py, how can i define sv without starting execution?
My Django unit tests have stopped working. Instantiating the Django test client now fails with the following error:
Traceback (most recent call last):
File "/vagrant/my/app/tests.py", line 43, in setUp
self.client = Client(HTTP_USER_AGENT='Mozilla/5.0')
File "/usr/local/lib/python2.6/dist-packages/Django-1.4.1-py2.6.egg/django/db/models/base.py", line 367, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
TypeError: 'HTTP_USER_AGENT' is an invalid keyword argument for this function
They fail when I instantiate the Django test client.
from django.test.client import Client
...
class MyAppTestCase(TestCase):
base_fixtures = ['fixtures.json']
def setUp(self):
self.client = Client(HTTP_USER_AGENT='Mozilla/5.0') # fails here
self.setupSession()
self.authenticateUser()
When I run python manage.py shell and enter the following, it works fine.
vagrant#lucid32:/var/www/mytraps.com/spensa$ python manage.py shell
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.test.client import Client
>>> client = Client(HTTP_USER_AGENT='Mozilla/5.0')
>>>
Any thoughts on why it is chocking on the HTTP_USER_AGENT keyword?
I found the solution.
I had a model class named 'Client'. My models were imported after the django test Client class.
You can't fix stupid.
I am using the external library IMAPClient. When the login fails, i see this error : imaplib.error: [AUTHENTICATIONFAILED] Authentication failed.
When i try except imaplib.error: i get : AttributeError: 'module' object has no attribute 'error'
The documentation of imaplib says that the exception should be IMAP4.error
Then why is IMAPClient raising imaplib.error and how do i catch it ?
The error message you see:
imaplib.error: [AUTHENTICATIONFAILED] Authentication failed.
is describing the error as best it knows how; at the time the exception occurs, the exception class is called "imaplib.error", because whoever is raising it has described it that way (more on this later). I poked around, and I think I've found it for you:
Python 2.7.2 (default, Nov 14 2011, 19:37:59)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imaplib
>>> imaplib.IMAP4.error
<class 'imaplib.error'>
I opened up the imaplib.py file, and found what seems like an odd exception-throwing mechanism. "IMAP4" is a class, and "error" is a class defined inside the IMAP4 class. Python doesn't appear to "nest" the classes - just the class definitions. So once an object of class "error" exists, it's an object of class "error" which was defined in the scope "imaplib". The fact that the "error" class definition was inside the "IMAP4" class lib definition is irrelevant to Python. On the other hand, in order for you to describe an object of class "error" before such an object exists, you need to reference it as imaplib.IMAP4.error in order for Python to find the definition of the class you are talking about.
Very confusing, I know, and I didn't really know all of this before I started investigating the question. Here's a brief illustration:
Python 2.7.2 (default, Nov 14 2011, 19:37:59)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo(object):
... class bar(object):
... pass
... def b(self):
... return bar()
...
>>> bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>> foo.bar
<class '__main__.bar'>
>>> foo().bar()
<__main__.bar object at 0x10048dd10>
Basically, you were trying to do a very reasonable thing, but the way the imaplib library handles exception throwing is a little odd, making your life difficult. Long story short, you should try to catch imaplib.IMAP4.error and move on with your life.
(Disclaimer: I'm the maintainer of IMAPClient)
IMAPClient uses imaplib under the hood which is why you're seeing imaplib errors when using it. To simplify things a little, imaplib's exceptions are aliased on to the IMAPClient class. To catch errors from IMAPClient you can do something like this:
from imapclient import IMAPClient
try:
client = IMAPClient(...)
client.do_something(...)
client.logout()
except IMAPClient.Error, err:
# handle error here
Error is the base exception class (same as imaplib.IMAP4.error). There's also AbortError and ReadOnlyError.
IMAPClient uses these exceptions when it raises errors itself so there's only one set of exceptions to worry about in your code.