Django - can I have 2 many to many fields to another model? - python

I'm developing an application that has the following three models: Student, Subject and Skills. A Student can have many skills, and a Skill can have many student. A Subject can offer 0 or many skills after a Student complete it, however, a Student has to have 0 or many skills required to complete a Subject.
I tried doing the following:
Subject
class Subject(models.Model):
name = models.CharField(max_length=50, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='subjects', default=0)
code = models.CharField(primary_key=True,verbose_name='Code', max_length=50)
description = models.CharField(max_length=100, blank=True)
offered_skills = models.ManyToManyField(Skill, related_name='subjects_o', blank=True)
required_skills = models.ManyToManyField(Skill, related_name='subjects_r', blank=True)
Skill
class Skill(models.Model):
code = models.CharField(primary_key=True,verbose_name='Code', max_length=50)
name = models.CharField(max_length=50, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='skills', default=0)
description = models.CharField(max_length=100, blank=True)
students = models.ManyToManyField(Student, related_name='skills', blank=True)
Student
class Student(models.Model):
code = models.CharField(primary_key=True, verbose_name='Codigo', max_length=50)
name = models.CharField(max_length=50, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='students', default=0)
description = models.CharField(max_length=100, blank=True)
When I try makemigrations it leads me to the following error:
Traceback (most recent call last):
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1149, in __init__
to._meta
AttributeError: module 'dashboard.models.Skill' has no attribute '_meta'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute
django.setup()
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/mnt/c/Users/isaac/OneDrive/Documentos/GitHub/ano_letivo/dashboard/models/__init__.py", line 4, in <module>
from .Skill import Skill
File "/mnt/c/Users/isaac/OneDrive/Documentos/GitHub/ano_letivo/dashboard/models/Skill.py", line 5, in <module>
class Skill(models.Model):
File "/mnt/c/Users/isaac/OneDrive/Documentos/GitHub/ano_letivo/dashboard/models/Skill.py", line 11, in Skill
offered_skills = models.ManyToManyField(Skill, related_name='subjects_o', blank=True)
File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1151, in __init__
assert isinstance(to, str), (
AssertionError: ManyToManyField(<module 'dashboard.models.Skill' from '/mnt/c/Users/isaac/OneDrive/Documentos/GitHub/ano_letivo/dashboard/models/Skill.py'>) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string 'self'
What could this be? When I take off the two last attributes of Subject the error vanishes. How could I modelate this?

Related

Missing fields after migration in Django project

I am interested in learning python and Django and I've started this course.
I am having difficulties in migrating the models in the project. Following the course, on chapter "Models".
I've inserted the given code in the boards/models.py file as instructed. The code:
from django.db import models
from django.contrib.auth.models import User
class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100)
class Topic(models.Model):
subject = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board, related_name='topics')
starter = models.ForeignKey(User, related_name='topics')
class Post(models.Model):
message = models.TextField(max_length=4000)
topic = models.ForeignKey(Topic, related_name='posts')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True)
created_by = models.ForeignKey(User, related_name='posts')
updated_by = models.ForeignKey(User, null=True, related_name='+')`
Following the instructions to the "Migrating the Models" chapter and running this command:
"python manage.py makemigrations" I should receive the following message:
Migrations for 'boards':
boards/migrations/0001_initial.py
- Create model Board
- Create model Post
- Create model Topic
- Add field topic to post
- Add field updated_by to post
Instead, I get the following errors:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "D:\Desktop\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "D:\Desktop\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "D:\Desktop\myproject\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\Desktop\myproject\venv\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "D:\Desktop\myproject\venv\lib\site-packages\django\apps\config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Zinkov\AppData\Local\Programs\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\Desktop\myproject\myproject\boards\models.py", line 8, in <module>
class Topic(models.Model):
File "D:\Desktop\myproject\myproject\boards\models.py", line 11, in Topic
board = models.ForeignKey(Board, related_name='topics')
TypeError: __init__() missing 1 required positional argument: 'on_delete'`
I've added the missing argument "on_delete" on the following lines:
board = models.ForeignKey(Board, related_name='topics', on_delete=models.CASCADE)
starter = models.ForeignKey(User, related_name='topics', on_delete=models.CASCADE)
topic = models.ForeignKey(Topic, related_name='posts',max_length=256, on_delete=models.CASCADE)
created_by = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
updated_by = models.ForeignKey(User, null=True, related_name='+',max_length=256, on_delete=models.CASCADE)`
After running the "makemigrations" command again the migration was successful but without adding the fields as expected.
My output is:
Migrations for 'boards':
boards\migrations\0001_initial.py
- Create model Board
- Create model Topic
- Create model Post
Instead of:
Migrations for 'boards':
boards\migrations\0001_initial.py
- Create model Board
- Create model Topic
- Create model Post
- Add field topic to post
- Add field updated_by to post
I am sorry for the long post.
Thank you!
While creating model where you have used ForeignKey relation it accepts on_delete argument and that is missing. Adding it should work.
Kindly refer to below code
class Topic(models.Model):
subject = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board, related_name='topics', on_delete=models.SET_NULL)
starter = models.ForeignKey(User, related_name='topics', on_delete=models.SET_NULL)
You can refer to this link for more on_delete arguments [https://www.geeksforgeeks.org/python-relational-fields-in-django-models/]

Getting an Error when running makemigrate on Product model fields that have been added to an existing model

Admittedly I’m a newbie to django and I’m getting the following error when trying to run python manage.py makemigrations
I’m trying to add a new field in to my class Product(models.Model):
featured = models.BooleanField()
Code
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120) # max_length = required
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=10000)
summary = models.TextField()
featured = models.BooleenField() #only new added line
Error: AttributeError: module 'django.db.models' has no attribute 'BooleenField'
command:
python manage.py makemigrations <enter>
entire_traceback:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\.....\trydjango\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\.....\trydjango\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\.....\trydjango\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\.....\trydjango\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\.....\src\products\models.py", line 4, in <module>
class Product(models.Model):
File "C:\.....\src\products\models.py", line 9, in Product
featured = models.BooleenField()
AttributeError: module 'django.db.models' has no attribute 'BooleenField'
There is an error in your code for the Product models.
I have corrected it.
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=120) # max_length = required
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=10000)
summary = models.TextField()
featured = models.BooleanField() #only new added line
the default value for a boolean field is always false.

from adaptor.model import CsvModel

I am trying to use the CsvModel module from django-adaptors. However, when i use from adaptor.model import CsvModel and makemigrations, below errors occured.
Can anyone advise the reason why? my code in the model is as follows:
from django.db import models
from adaptor.model import CsvModel
from adaptor.fields import CharField, DecimalField
class User(models.Model):
user_name = models.CharField(max_length = 50, null=True, unique=True)
def __str__(self):
return self.user_name
class Profile(models.Model):
rubbish = models.DecimalField(max_digits= 1000, decimal_places=3, null=True)
user = models.CharField(max_length = 50, unique = True, null=True)
hobby = models.CharField(max_length = 50, null=True)
job = models.CharField(max_length = 60, null=True)
class Trial(CsvModel):
rubbish = DecimalField()
user = CharField()
hobby = CharField()
class Meta:
dbmodel = Profile
delimiter = ','
has_header = True
Error message is as follows:
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/pangkachun/Desktop/smallpro2/small_pro/small/models.py", line 2, in <module>
from adaptor.model import CsvModel
File "/usr/local/lib/python3.6/site-packages/adaptor/model.py", line 269
except ValueError, e:
^ . `
You are using python3.6 but the library looks like it is made for python2.5-
For Python 3 it should be
except ValueError as e:
source
You may have to find a different csv plugin like django-csvimport and possibly change your strategy accordingly

Migration error in django models.py database

My app is installed correctly and its models.py reads:
from django.db import models
class Album(models.Model):
artist = models.CharField(max_lenght=250)
album_title = models.CharField(max_lenght=500)
genre = models.CharField(max_lenght=100)
album_logo = models.CharField(max_lenght=1000)
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_lenght=10)
song_title = models.CharField(max_lenght=250)
But whenever I run python manage.py migrate, I get the following error:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 347, in execute
django.setup()
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 3, in <module>
class Album(models.Model):
File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 4, in Album
artist = models.CharField(max_lenght=250)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\db\models\fields\__init__.py", line 1042, in __init__
super().__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'max_lenght'
What could be wrong? I'm still a beginner and I'm still learning about databases.
Use this:
As per my comment, length (lenght) splelling is wrong.
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.TextField()
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
You have spelled length wrong here
album_title = models.CharField(max_lenght=500)
happens to the best of us.

Django module object is not iterable

I'm currently trying to build a blog using Django. I've been facing this error for a few hours now. I'm not quite sure if this has anything to do with the directories but the error occurs when I try to register my model in the admin.py file.
from django.contrib import admin
from .models import Post
# Register models
admin.site.register(Post)
The directories look as follows:
blog
models
Post
Category
admin.py
settings
static
templates
Trace:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7ffb589a67b8>
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run
autoreload.raise_last_exception()
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute
autoreload.check_errors(django.setup)()
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate
app_config.ready()
File "/usr/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/hallak/Projects/hallak.io/hallak_blog/admin.py", line 5, in <module>
admin.site.register(Post)
File "/usr/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 102, in register
for model in model_or_iterable:
TypeError: 'module' object is not iterable
Post:
from django.db import models
from django.utils import timezone
class Post(models.Model):
# Auto-generated ID
id = models.AutoField(primary_key=True)
# Title
title = models.CharField(max_length=100)
# Slug
slug = models.SlugField(max_length=100)
# Content
body = models.TextField()
# Timestamps
created_on = models.DateField(auto_now_add=True)
published_on = models.DateTimeField(blank=True, null=True)
# Category
category = models.ForeignKey('.Category', on_delete=models.DO_NOTHING)
# Author
author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING)
# Publish post
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Category:
from django.db import models
class Category(models.Model):
# Auto-generated ID
id = models.AutoField(primary_key=True)
# Title
title = models.CharField(max_length=100)
# Slug
slug = models.SlugField(max_length=100)
# Timestamps
created_on = models.DateField(auto_now_add=True)
The error is happening here: https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L100-L101
Whenever I comment the register line everything works fine.
Instead of writing "from .models import Post" you should write "from .models.Post import Post".
First "Post" is a modulename (file name), second one is a class name.

Categories