I was trying to build a model for the profile details of the user of my django web app like:
class UserDetails(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
profilePicture = models.ImageField(blank = True, upload_to='profile_pics/'+self.user.id+'/')
country = models.CharField(max_length = 50, default='India')
gender = models.CharField(max_length=10, default='NA')
birthday = models.DateField(default=datetime.now())
phone = models.CharField(max_length=15)
I have an image field in the above model and I want to upload the incoming images to the path profile_pics/<id of the user whose profile is being set up>/ within my media storage path. I tried to do that by specifying the upload_to attribute of the image field as upload_to = 'profile_pics/'+self.user.id+'/'. I am using AWS S3 for my media storage and I have put the necessary settings in my settings as:
AWS_ACCESS_KEY_ID = 'myaccesskeyid'
AWS_SECRET_ACCESS_KEY = 'mysecretaccesskey'
AWS_STORAGE_BUCKET_NAME = 'mybucketname'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
When I try to make the migrations, I get the following error:
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 "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute
django.setup()
File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/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/suraj/Work/treeapp/treeapp-backend/userMgmt/models.py", line 7, in <module>
class UserDetails(models.Model):
File "/home/suraj/Work/treeapp/treeapp-backend/userMgmt/models.py", line 9, in UserDetails
profilePicture = models.ImageField(blank = True, upload_to='profile_pics/'+self.user.id+'/')
NameError: name 'self' is not defined
Please help me out to set the default path of the image uploads to this model to profile_pics/<id of the user whose profile is being set up>/.
You can pass a callable to the upload_to=… parameter [Django-doc]:
class UserDetails(models.Model):
def profile_picture_upload(self, filename):
return 'profile_pics/{}/{}'.format(self.user_id, filename)
# …
profilePicture = models.ImageField(blank=True, upload_to=profile_picture_upload)
Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: profile_picture instead of profilePicture.
Related
I created two models in my Django db. Now, I want to make migrations, but it shows error like this: AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb' . I tried to google the answer and found that this signal was deprecated in new Django version. It is not my project and I can't change the current version, so my colleagues recommended me to find the solution. What am I supposed to do if I can't change the version of Django and working on dev branch in project? How do I make migrations? What packages I can update?
My models:
class Categories(models.Model):
name = models.CharField(max_length=100)
position = models.IntegerField(unique=True)
def __str__(self):
return self.name
#classmethod
def get_default_pk(cls):
obj, created = cls.objects.get_or_create(
name='No category was added',
position=99
)
return obj.pk
class Shop(models.Model):
name = models.CharField(_('shop name'), max_length=128)
domain = models.CharField(_('domain'), max_length=128)
active = models.BooleanField(_('active'), default=True)
position = models.PositiveSmallIntegerField(_('position'), default=0)
category = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='related_name_category',
default=Categories.get_default_pk())
class Meta:
ordering = ('position', 'name')
verbose_name = _('shop')
verbose_name_plural = _('shops')
def __str__(self):
return self.name
The whole traceback after running python3 manage.py makemigrations:
Traceback (most recent call last):
File "/Users/ArtemBoss/GitHubRepos/pricemon/manage.py", line 22, in <module>
main()
File "/Users/ArtemBoss/GitHubRepos/pricemon/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute
django.setup()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate
app_config.import_models()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/constance/models.py", line 30, in <module>
signals.post_syncdb.connect(create_perm, dispatch_uid="constance.create_perm")
AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb'
Make sure that no model in your project uses post_syncdb as if so, it will prevent you from running the migrations command.
Also why can't you use an appropriate version of Django?
I am developing a Student management system in django and while making it I got this
class Dept(models.Model):
id = models.CharField(primary_key='True', max_length=100)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Course(models.Model):
dept = models.ForeignKey(Dept, on_delete=models.CASCADE)
id = models.CharField(primary_key='True', max_length=50)
name = models.CharField(max_length=50)
shortname = models.CharField(max_length=50, default='X')
def __str__(self):
return self.name
and while doing make migrations I get this error
by what means Can I get this right and how can I tackle this error
(studentmanagementsystem) C:\Users\harsh\dev\student management\student_management>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\harsh\anaconda3\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\harsh\anaconda3\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\harsh\anaconda3\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\harsh\anaconda3\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 843, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\harsh\dev\student management\student_management\student_app\models.py", line 10, in <module>
class Dept(models.Model):
File "C:\Users\harsh\dev\student management\student_management\student_app\models.py", line 18, in Dept
class Course(models.Model):
File "C:\Users\harsh\dev\student management\student_management\student_app\models.py", line 19, in Course
dept = models.ForeignKey(Dept, on_delete=models.CASCADE)
NameError: name 'Dept' is not defined
(studentmanagementsystem) C:\Users\harsh\dev\student management\student_management>
Honestly, I do not know why you were getting this error as what you have shown here in the example is correct. The only times (at least that I know of) you get this error is when:
The two models are defined in different files and there is a problem with importing the relationship model.
The model that the relationship is being created with is defined after the relationship. In your example, it would mean defining the Dept model after the Course model.
You can import your models as a string using APP_NAME.MODEL_NAME, which avoids such cases, specially the second scenario I have described.
class Course(models.Model):
# Assuming your model resides in an app called 'student_app'
dept = models.ForeignKey('student_app.Dept', on_delete=models.CASCADE)
i have this project where there is a Login app and there is a Homepage app. The project files look like this
login
homepage
models.py
login
settings.py
urls.py
usersignup
models.py
manage.py
Here is usersignup/models.py
'''
from django.db import models
class UserDetail(models.Model):
first_name = models.CharField(max_length=225)
middle_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255)
email = models.EmailField()
def __str__(self):
return self.first_name
class WebDetail(UserDetail):
# user = models.OneToOneField(UserDetail, on_delete=models.CASCADE, primary_key=True,)
username = models.CharField(max_length=255)
password = models.CharField(max_length=255)
'''
and here is homepage/models.py
'''
from django.db import models
from login.usersignup.models import UserDetail
class UploadProfilePicture(models.Model):
caption = models.CharField(max_length=2000)
image = models.ImageField(upload_to='images/')
class Profile(models.Model):
user = models.ForeignKey(UserDetail, on_delete=models.CASCADE)
'''
and when i run
'''
python manage.py check
'''
i get this error
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 "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\core\management\__init__.py", line 401,
in execute_from_command_line
utility.execute()
File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\core\management\__init__.py", line 377,
in execute
django.setup()
File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\apps\config.py", line 211, in import_mod
els
self.models_module = import_module(models_module_name)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_modul
e
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:\Users\user\Documents\McDonald\Login\login\homepage\models.py", line 2, in <module>
from login.usersignup.models import UserDetail
ModuleNotFoundError: No module named 'login.usersignup'
so, is there any way i could import the UserDetail class in the usersignup/models to the homepage/models?
Thanks for your contribution
Instead of using :
from login.usersignup.models import UserDetail
try using this :
from usersignup.models import UserDetail
I'm tying to create template filter, which will take value and search it in my model
import django
django.setup()
tried this it didn't help
Here is my code
catalog_custom_tags.py
from catalog import models
from django import template, shortcuts
register = template.Library()
#register.filter(name='test')
def test(value):
item = shortcuts.get_object_or_404(models.Equipment, pk=value)
return item.name
models.py
from django.db import models
class EquipmentCategory(models.Model):
name = models.CharField(verbose_name="Name", max_length=30, unique=True)
category = models.CharField(verbose_name="Category", max_length=20, unique=True)
def __str__(self):
return self.name
class EquipmentSubCategory(models.Model):
name = models.CharField(verbose_name="Name", max_length=30, unique=True)
category = models.ForeignKey(EquipmentCategory, on_delete=models.CASCADE)
subcategory = models.CharField(verbose_name="Sub Category", max_length=20, unique=True)
def __str__(self):
return self.name
class Material(models.Model):
name = models.CharField(verbose_name="Name", max_length=30, unique=True)
material = models.CharField(verbose_name="Material", max_length=30, unique=True)
def __str__(self):
return self.name
class Equipment(models.Model):
name = models.CharField(verbose_name="Name", max_length=30)
# category = models.CharField(verbose_name="Category", max_length=20)
# subcategory = models.CharField(verbose_name="Sub Category", max_length=20)
category = models.ForeignKey(EquipmentCategory, on_delete=models.CASCADE)
subcategory = models.ForeignKey(EquipmentSubCategory, on_delete=models.CASCADE)
dimension_x = models.IntegerField(verbose_name="Dimensions X(cm)", default=0)
dimension_y = models.IntegerField(verbose_name="Dimensions Y(cm)", default=0)
dimension_z = models.IntegerField(verbose_name="Dimensions Z(cm)", default=0)
weight = models.FloatField(verbose_name="Weight(kg)", default=0)
qty = models.IntegerField(verbose_name="Quantity", default=0)
image = models.ImageField(verbose_name="Foto", blank=True, upload_to='fotos/', max_length=20)
accessories = models.TextField(verbose_name="accessories", blank=True)
material = models.ForeignKey(Material, on_delete=models.CASCADE)
# material = models.CharField(verbose_name="Material", max_length=20, null=True)
color = models.CharField(verbose_name="Color", max_length=20, null=True)
location = models.CharField(verbose_name="Location", blank=True, max_length=20)
description = models.TextField(verbose_name="Description", blank=True)
def __str__(self):
return self.name
And i get this error
File "C:\Users\mro\PycharmProjects\EuroWeb\catalog\templatetags\catalog_custom_tags.py", line 1, in <module>
from catalog import models
File "C:\Users\mro\PycharmProjects\EuroWeb\catalog\models.py", line 4, in <module>
class EquipmentCategory(models.Model):
and Apps not loaded error
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Full traceback
Traceback (most recent call last):
File "C:/Users/mro/PycharmProjects/EuroWeb/manage.py", line 21, in <module>
main()
File "C:/Users/mro/PycharmProjects/EuroWeb/manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\core\management\__init__.py", line 325, in execute
settings.INSTALLED_APPS
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
self._setup(name)
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\conf\__init__.py", line 66, in _setup
self._wrapped = Settings(settings_module)
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\conf\__init__.py", line 157, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Users\mro\AppData\Local\Programs\Python\Python36\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\mro\PycharmProjects\EuroWeb\EuroWeb\settings.py", line 140, in <module>
django.setup()
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "C:\Users\mro\AppData\Local\Programs\Python\Python36\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\mro\PycharmProjects\EuroWeb\catalog\templatetags\catalog_custom_tags.py", line 1, in <module>
from catalog import models
File "C:\Users\mro\PycharmProjects\EuroWeb\catalog\models.py", line 4, in <module>
class EquipmentCategory(models.Model):
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\db\models\base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
The file structure should be something like this.
polls/
__init__.py
models.py
templatetags/
__init__.py
poll_extras.py
views.py
and in template
{% load poll_extras %}
https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#code-layout
ok... i found a solution. I appreciate if some one can tell me why this happens...
the solution is:
to put filter which cause this error into another file
I am getting an error when trying to syncdb through the command line.
My goal is a basic music search/delete/update/add application with certain criteria and I am using Python and Django.
The class I'm trying to write:
from django.db import models
# music search
class musicsearch(models.Model):
id = models.IntegerField
title = models.CharField(max_length=40)
artist = models.CharField(max_length=40)
genre = models.CharField(max_length=20)
The error traceback:
C:\Users\jodie\Desktop\NtokloMH>python manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 354, in execute
django.setup()
File "C:\Python34\lib\site-packages\django\__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Python34\lib\site-packages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "C:\Users\jodie\Desktop\NtokloMH\musicsearch\models.py", line 4, in <module>
class musicsearch(models.Model):
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 168, in __new__
new_class.add_to_class(obj_name, obj)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 297, in add_to_class
value.contribute_to_class(cls, name)
TypeError: contribute_to_class() missing 1 required positional argument: 'name'
I can see two issues with your model.
You didn't create an instance of the IntegerField; you need to call it:
id = models.IntegerField()
# ^^
You are creating tuples for the other fields, because you end each field with a comma:
title = models.CharField(max_length=40),
# ^
Remove those commas.
You don't really have to specify your own id field; models are by default given an id field automatically. See Automatic primary fields in the Django models documentation:
By default, Django gives each model the following field:
id = models.AutoField(primary_key=True)
This is an auto-incrementing primary key.
Since your specified your own id field that doesn't use primary_key=True, your model is probably going to run into problems with that too.
Below line of code is missing
id = models.IntegerField(primary_key= True)
You are missing two () for your id integerfield.
id = models.IntegerField()