I have a many-to-many to many type models. I use a script to populate the database. However I want to print the objects and save it only if i want it to be saved using a y/n style input. The problem is I can't create the objects without saving them as you can see below.
>>> mov = Movie(name="completenothing")
>>> direc = Director(name="Someone")
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Director: Someone>" needs to have a value for field "id" before this many-to-many relationship can be used.
>>> direc.save()
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 1060, in _add_items
(obj, self.instance._state.db, obj._state.db)
ValueError: Cannot add "<Movie: completenothing N/A>": instance is on database "default", value is on database "None"
>>> mov.save()
>>> direc.movie_name.add(mov)
Director and Movie are in a many-to-many relation and i want their information displayed before saving. Is there some mechanism to allow this ?
If you use a pre_save signal, you can try this.
from django.db.models.signals import pre_save
def confirm_save(sender, instance, **kwargs):
# do something with your instance (display information)
ans = input("Do you want to save(y/n)")
if ans == 'y':
print("Your instance saved successfully")
else:
raise Exception("Not saved")
pre_save.connect(confirm_save, sender=MyModel)
Related
I was attempting to create a custom model field and use it in a model as the docs demonstrate for BetterCharField shown here (you might have to scroll a bit down): https://docs.djangoproject.com/en/3.0/howto/custom-model-fields/#custom-database-types
My code in my models.py is as follows, almost verbatim from the docs example:
from django.db import models
# Create your models here.
class BetterCharField(models.Field):
def __init__(self, max_length, *args, **kwargs):
self.max_length = max_length
super().__init__(*args, **kwargs)
def db_type(self, connection):
return "char({})".format(self.max_length)
class MyModel(models.Model):
my_field = BetterCharField(25)
However, when trying to run python manage.py makemigrations with this models.py file, I get the following error every time:
Traceback (most recent call last):
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/db/migrations/state.py", line 413, in from_model
fields.append((name, field.clone()))
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 512, in clone
return self.__class__(*args, **kwargs)
TypeError: __init__() missing 1 required positional argument: 'max_length'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 142, in handle
ProjectState.from_apps(apps),
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/db/migrations/state.py", line 221, in from_apps
model_state = ModelState.from_model(model)
File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/db/migrations/state.py", line 418, in from_model
e,
TypeError: Couldn't reconstruct field my_field on polls.MyModel: __init__() missing 1 required positional argument: 'max_length'
Why is this failing? I had yet to create any migrations at all for this project, let alone the field and model given here. I have my positional argument as 25 given to BetterCharField when I initialize it in my models.py file. What am I missing? I had a much more complex use case, but I built this example in a brand new test django project/app straight from the documentation, and it still fails.
This is documented behaviour:
You can’t modify the number of positional arguments in an already migrated custom field without raising a TypeError. The old migration will call the modified __init__ method with the old signature. So if you need a new argument, please create a keyword argument and add something like assert 'argument_name' in kwargs in the constructor.
My model is like this
class Profile(models.Model):
user = models.OneToOneField(User,default=None,null=True,on_delete=models.CASCADE)
name = models.CharField(max_length=50,null=True)
i am trying to get through models using shell but getting the empty query.
I tried this
>>> u1=User.objects.get(username='gautam')
>>>u1
<User: gautam>
>>> Profile.objects.get(user=u1)
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/home/gautam/.local/lib/python3.6/site-
packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/gautam/.local/lib/python3.6/site-
packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
homes_login.models.DoesNotExist: Profile matching query does not
exist.
I am tring to get the user for that profile.
This profile is simply not created. Setting an OneToOne relation doesn't guarantee that profile will exist for each user. To overcome that, you should simply create new profile, like this:
>>> Profile.objects.create(user=u1)
To automate process of getting existing profile or creating new one, you can use get_or_create method.
I'm having a problem with deleting ADUser.
pyad.set_defaults(ldap_server="dc1.domain.com", username="service_account", password="mypassword")
user = aduser.ADUser.from_dn("cn=myuser, ou=staff, dc=domain, dc=com")
user.delete()
Unfortunately I could not figure out how to format this text to look like a real traceback
Traceback (most recent call last):
File "C:/Automation/qa/robot2/python_lib/keywords/AD/unittest.py", line 34,
in <module>
ad_connect.bg_ad_user_remove(user_login='vasya.oconnor#test-acme.com',dn_string= dn_string)
File "C:\Automation\qa\robot2\python_lib\keywords\AD\_bg_ad_general.py", line 156, in bg_ad_user_remove
user.delete()
File "C:\Python27\lib\site-packages\pyad\adobject.py", line 537, in delete
if not parent:
File "C:\Python27\lib\site-packages\future\types\newobject.py", line 90, in __nonzero__
return type(self).__len__(self)
AttributeError: type object 'ADContainer' has no attribute '__len__'
I am trying to get going with django, which so far I have found to be amazing other than repeated db issues.
My latest is following the Django by Example book and I have followed everything to the letter, yet when following some simple instructions to add some data via the python shell api I get the following:
>>> from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='jamie')
>>> Post.objects.create(title='One More Post', slug='one-more-post', body='Post body', author='user')
Traceback (most recent call last):
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle
self.run_shell(shell=options['interface'])
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/base.py", line 468, in __init__
setattr(self, field.name, rel_obj)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 629, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "'user'": "Post.author" must be a "User" instance.
This has happened while following multiple tutorials and I am stumped. I followed standard instructions and installed, pip, python and django via terminal. Also using a virtual env so not sure why this is happening.
Use this instead of your statement.
Use user variable instead of 'user' string.
Post.objects.create(title='One More Post', slug='one-more-post',
body='Post body', author=user)
I have a password-protected private key in a .pem file; I want to use it to sign requests to a remote server. I'm able to load the key and enter the passphrase after being prompted for it:
python
>>> import M2Crypto
>>> pk = M2Crypto.RSA.load_key('private.pem')
Enter passphrase:
>>>
However, I need this for a server process which is restarted every morning, and thus the passphrase must be passed automatically somehow. The load_key method supports a callback argument for this purpose, so I tried several variants of:
>>> def gimmepw():
... return 'mysecret'
...
>>> pk = M2Crypto.RSA.load_key('private.pem', gimmepw)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/local/Plone/Python-2.4/.../M2Crypto/RSA.py", line 351, in load_key
return load_key_bio(bio, callback)
File "/usr/local/Plone/Python-2.4/.../M2Crypto/RSA.py", line 372, in load_key_bio
rsa_error()
File "/usr/local/Plone/Python-2.4/.../M2Crypto/RSA.py", line 302, in rsa_error
raise RSAError, m2.err_reason_error_string(m2.err_get_error())
M2Crypto.RSA.RSAError: bad password read
>>>
(replace "..." by "lib/python2.4/site-packages")
What am I doing wrong?
This is due to the lack of parameter support in your callback function. As it will be called with at least one parameter, a TypeError exception will occurred (which is catched by M2Crypto).
>>> def gimmepw(*args):
... print 'args:', repr(args)
... return 'test'
...
>>> M2Crypto.RSA.load_key('key.pem', gimmepw)
args: (0,)
<M2Crypto.RSA.RSA instance at 0xb6e8050c>
You should try:
def gimmepw(*args):
return 'mysecret'
One caveat: As of Python 2.7, the return value of your callback method must return a str type.
For example, a unicode type will error out in the same way.
>>> def gimmepw(*args):
... return u'test'
...
>>> M2Crypto.RSA.load_key('key.pem', gimmepw)
Traceback (most recent call last):
File "test_intuit_data.py", line 76, in <module>
intuit_rsa_key = RSA.load_key(file='key.pem', callback=gimmepw)
File "lib/python2.7/site-packages/M2Crypto/RSA.py", line 351, in load_key
return load_key_bio(bio, callback)
File "lib/python2.7/site-packages/M2Crypto/RSA.py", line 372, in load_key_bio
rsa_error()
File "lib/python2.7/site-packages/M2Crypto/RSA.py", line 302, in rsa_error
raise RSAError, m2.err_reason_error_string(m2.err_get_error())
M2Crypto.RSA.RSAError: bad password read
If you are using any input other than a str type, be sure to cast to a str appropriately:
>>> def gimmepw(*args):
... return str(u'test')
...
>>> M2Crypto.RSA.load_key('key.pem', gimmepw)
<M2Crypto.RSA.RSA instance at 0xb6e8050c>