👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
I have two classes in my sqlite database, a parent table named Categorie
and the child table called Article
. I created first the child table class and addes entries. So first I had this:
class Article(models.Model):
titre=models.CharField(max_length=100)
auteur=models.CharField(max_length=42)
contenu=models.TextField(null=True)
date=models.DateTimeField(
auto_now_add=True,
auto_now=False,
verbose_name="Date de parution"
)
def __str__(self):
return self.titre
And after I have added parent table, and now my models.py
looks like this:
from django.db import models
# Create your models here.
class Categorie(models.Model):
nom = models.CharField(max_length=30)
def __str__(self):
return self.nom
class Article(models.Model):
titre=models.CharField(max_length=100)
auteur=models.CharField(max_length=42)
contenu=models.TextField(null=True)
date=models.DateTimeField(
auto_now_add=True,
auto_now=False,
verbose_name="Date de parution"
)
categorie = models.ForeignKey("Categorie")
def __str__(self):
return self.titre
So when I run python manage.py makemigrations <my_app_name>
, I get this error:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:UserslislisAppDataLocalProgramsPythonPython35-32libsite-packagesdjango-2.0-py3.5.eggdjangocoremanagement\__init__.py", line 354, in execute_from_command_line
utility.execute()
File "C:UserslislisAppDataLocalProgramsPythonPython35-32libsite-packagesdjango-2.0-py3.5.eggdjangocoremanagement\__init__.py", line 330, in execute
django.setup()
File "C:UserslislisAppDataLocalProgramsPythonPython35-32libsite-packagesdjango-2.0-py3.5.eggdjango\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:UserslislisAppDataLocalProgramsPythonPython35-32libsite-packagesdjango-2.0-py3.5.eggdjangoapps
egistry.py", line 112, in populate
app_config.import_models()
File "C:UserslislisAppDataLocalProgramsPythonPython35-32libsite-packagesdjango-2.0-py3.5.eggdjangoappsconfig.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:UserslislisAppDataLocalProgramsPythonPython35-32libimportlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:UserslislisDjangomon_sitelogmodels.py", line 6, in <module>
class Article(models.Model):
File "C:UserslislisDjangomon_sitelogmodels.py", line 16, in Article
categorie = models.ForeignKey("Categorie")
TypeError: __init__() missing 1 required positional argument: "on_delete"
I"ve seen some similar issues in stackoverflow, but it seems to not be the same problem: __init__() missing 1 required positional argument: 'quantity'
👻 Read also: what is the best laptop for engineering students?
Getting TypeError: __init__() missing 1 required positional argument: "on_delete" when trying to add parent table after child table with entries __del__: Questions
How can I make a time delay in Python?
5 answers
I would like to know how to put a time delay in a Python script.
Answer #1
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
Here is another example where something is run approximately once a minute:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
Answer #2
You can use the sleep()
function in the time
module. It can take a float argument for sub-second resolution.
from time import sleep
sleep(0.1) # Time in seconds
Getting TypeError: __init__() missing 1 required positional argument: "on_delete" when trying to add parent table after child table with entries __del__: Questions
How to delete a file or folder in Python?
5 answers
How do I delete a file or folder in Python?
Answer #1
os.remove()
removes a file.os.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.
Answer #2
os.remove()
removes a file.os.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.
Answer #3
Python syntax to delete a file
import os
os.remove("/tmp/<file_name>.txt")
Or
import os
os.unlink("/tmp/<file_name>.txt")
Or
pathlib Library for Python version >= 3.4
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Path.unlink(missing_ok=False)
Unlink method used to remove the file or the symbolik link.
If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.
Best practice
- First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
a.os.path.isfile("/path/to/file")
b. Useexception handling.
EXAMPLE for os.path.isfile
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
## If file exists, delete it ##
if os.path.isfile(myfile):
os.remove(myfile)
else: ## Show an error ##
print("Error: %s file not found" % myfile)
Exception Handling
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
## Try to delete the file ##
try:
os.remove(myfile)
except OSError as e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename, e.strerror))
RESPECTIVE OUTPUT
Enter file name to delete : demo.txt Error: demo.txt - No such file or directory. Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted. Enter file name to delete : foo.txt
Python syntax to delete a folder
shutil.rmtree()
Example for shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir= raw_input("Enter directory name: ")
## Try to remove tree; if failed show an error using try...except on screen
try:
shutil.rmtree(mydir)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))
Is there a simple way to delete a list element by value?
5 answers
I want to remove a value from a list if it exists in the list (which it may not).
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
The above case (in which it does not exist) shows the following error:
Traceback (most recent call last):
File "D:zjm_codea.py", line 6, in <module>
b = a.index(6)
ValueError: list.index(x): x not in list
So I have to do this:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)
But is there not a simpler way to do this?
Answer #1
To remove an element"s first occurrence in a list, simply use list.remove
:
>>> a = ["a", "b", "c", "d"]
>>> a.remove("b")
>>> print(a)
["a", "c", "d"]
Mind that it does not remove all occurrences of your element. Use a list comprehension for that.
>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]
We hope this article has helped you to resolve the problem. Apart from Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries, check other __del__-related topics.
Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.
By the way, this material is also available in other languages:
- Italiano Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Deutsch Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Français Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Español Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Türk Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Русский Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Português Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Polski Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- Nederlandse Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- 中文 Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- 한국어 Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- 日本語 Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
- हिन्दी Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries
Milan | 2023-02-02
I was preparing for my coding interview, thanks for clarifying this - Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries in Python is not the simplest one. I am just not quite sure it is the best method
Boston | 2023-02-02
Simply put and clear. Thank you for sharing. Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries and other issues with Python functions was always my weak point 😁. I just hope that will not emerge anymore
Boston | 2023-02-02
I was preparing for my coding interview, thanks for clarifying this - Getting TypeError: __init__() missing 1 required positional argument: “on_delete” when trying to add parent table after child table with entries in Python is not the simplest one. Will use it in my bachelor thesis