User Profile 'Syntax Erro'r in Django - django

I am trying to create the user profile in Django. t is a new User model that inherits from AbstractUser. It requires special care and to update some references through the settings.py. Ideally, it should be done at the beginning of the project, since it will dramatically impact the database schema. Extra care while implementing it.
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/home/user/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/home/user/anaconda3/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 674, in exec_module
File "<frozen importlib._bootstrap_external>", line 781, in get_code
File "<frozen importlib._bootstrap_external>", line 741, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/user/Desktop/vmail/vm/models.py", line 21
user = models.OneToOneField(User, on_delete=models, CASCADE)
^
SyntaxError: positional argument follows keyword argument
how to solve this syntax error?
my models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class login(models.Model):
title=models.CharField(max_length=50, blank=True, null=True)
content=models.TextField(blank=True, null=True)
date=models.DateTimeField(default=timezone.now())
def __str__(self):
return self.title
class UserProfileModel(models.Model):
user = models.OneToOneField(User, on_delete=models, CASCADE)
gender = models.CharField(max_length='1', choices=(('M','Male'),('F','Female')), blank=True)
age = models.PositiveIntegerField(blank=True, null=True)
def __str__(self):
return self.user.username
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'

Change this to
user = models.OneToOneField(User, on_delete=models.CASCADE)

Related

AttributeError when I import model from another app

I don't know why but I got an error: AttributeError: module 'downloads.models' has no attribute 'AbstractDownload' in this place: class Download(models_downloads.AbstractDownload):
In download app I have already AbstractDownload class
Here is my model from products
products/models.py
from downloads import models as models_downloads
class Download(models_downloads.AbstractDownload):
product = models.ForeignKey('products.Product', related_name='downloads')
file = FilerFileField(related_name="file_products_download")
Here is downloads models
downloads/models.py
class AbstractDownload(models.Model):
title = models.CharField(max_length=500)
subtitle = models.CharField(max_length=1000, blank=True)
file = FilerFileField(related_name="file_abstract_download")
order = models.PositiveIntegerField(default=0)
class Meta:
abstract = True
def __str__(self):
return self.title
Traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/path/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/path/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute
django.setup()
File "/path/venv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/path/venv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/path/venv/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/path/venv/lib/python3.5/importlib/__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 "/path/www/downloads/models.py", line 6, in <module>
from products import models as products_models
File "/path/www/products/models.py", line 31, in <module>
class Download(models_downloads.AbstractDownload):
AttributeError: module 'downloads.models' has no attribute 'AbstractDownload'
You have a circular import. Your downloads/models.py has:
from products import models as products_models
But your products/models.py has
from downloads import models as models_downloads
You haven't shown how you use products_models, so we can't really say how to fix it. Here's a few suggestions:
Perhaps that import isn't necessary if you use a string for foreign keys, e.g. models.ForeignKey('downloads.ModelName')
Perhaps you could move AbstractDownload and Download so that they are in the same models, so that you don't need an import
If you use products_models inside a method, you could move the import inside the method. I would avoid this if possible.

ArrayField to store custom Field value

I want to use an arrayfield to store a list of json strings which represent a specific custom class. What I have done is:
from django.contrib.postgres.fields import JSONField, ArrayField
from django.db import models
# other imports
class MyCustomField(models.Field):
a = models.FloatField(blank=True, null=True)
b = models.DateTimeField()
c = JSONField(blank=True, null=True)
def db_type(self, connection):
return 'Text'
def rel_db_type(self, connection):
return 'integer UNSIGNED'
def to_python(self, value):
return json.loads(value)
def get_prep_value(self, value):
return json.dumps(value)
class A(models.Model):
# ... various normal fields here, then:
pres = ArrayField(MyCustomField)
def get_absolute_url(self):
return reverse('foo:bar', kwargs={'pk': self.id})
But:
python manage.py makemigrations
throws the following error
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/contrib/postgres/fields/array.py", line 75, in set_attributes_from_name
self.base_field.set_attributes_from_name(name)
TypeError: set_attributes_from_name() missing 1 required positional argument: 'name'
The full traceback is:
Traceback (most recent call last):
File "manage.py", line 13, in <module>
execute_from_command_line(sys.argv)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "<path_to_my_virtualenv_dir>/lib/python3.5/importlib/__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 673, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "<path_to_my_app>/models.py", line 62, in <module>
class SolarPrediction(models.Model):
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/db/models/base.py", line 157, in __new__
new_class.add_to_class(obj_name, obj)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/db/models/base.py", line 316, in add_to_class
value.contribute_to_class(cls, name)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 689, in contribute_to_class
self.set_attributes_from_name(name)
File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/contrib/postgres/fields/array.py", line 75, in set_attributes_from_name
self.base_field.set_attributes_from_name(name)
TypeError: set_attributes_from_name() missing 1 required positional argument: 'name'
Any thoughts on what I might be doing wrong?
Thanks
Try to define base_field attribute as standalone field - MyCustomField() istead of MyCustomField:
pres = ArrayField(MyCustomField())

pytest execute code before database created

In AdminForm I prevent the user from duplicating the records.
from django import forms
from django.contrib.auth.models import User
from apps.accounting_users.models import AccountingUser
from apps.marketing_users.models import MarketingUser
from apps.mgmt_users.models import ManagementUser
from apps.serv_mgrs_users.models import ServiceMgmtUser
from apps.serv_staff_users.models import ServiceStaffUser
class BaseDjangoAdminRoleForm(forms.ModelForm):
user = forms.ModelChoiceField(
queryset=User.objects.exclude(
username__in=[record.user.username for record in AccountingUser.objects.all()] +
[record.user.username for record in MarketingUser.objects.all()] +
[record.user.username for record in ManagementUser.objects.all()] +
[record.user.username for record in ServiceMgmtUser.objects.all()] +
[record.user.username for record in ServiceStaffUser.objects.all()],
)
)
mgmt_users/models.py
from apps.commons.models import AbstractSBrandUser
class ManagementUser(AbstractSBrandUser):
pass
commons/models
class AbstractSBrandUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True)
mobile = models.CharField(max_length=15)
class Meta:
abstract = True
OSX 10.12.4 pytest is normal
Debian:Jessie is broken
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/local/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/buddy/siam-sbrand/portal/apps/mgmt_users/admin.py", line 3, in <module>
from apps.commons.forms import BaseDjangoAdminRoleForm
File "/buddy/siam-sbrand/portal/apps/commons/forms.py", line 11, in <module>
class BaseDjangoAdminRoleForm(forms.ModelForm):
File "/buddy/siam-sbrand/portal/apps/commons/forms.py", line 17, in BaseDjangoAdminRoleForm
[record.user.username for record in ServiceMgmtUser.objects.all()] +
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 1087, in _fetch_all
Question:
I had checked the syntax based on python3 already.
And I had checked the filter syntax of Django1.10 already.
python manage.py shell run fine. No error at all.
How can I use queryset in the AdminForm of the Django and pass the test?
Do I need to sacrify testing for this feature?
You can't use querysets like [record.user.username for record in AccountingUser.objects.all()] in your model form definition. Django tries to evaluate the queryset when the module is loaded. If the table has not been created yet, this will give an error.
You can fix the problem by setting the queryset in the __init__ method.
class BaseDjangoAdminRoleForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.none())
def __init__(self, *args, **kwargs):
super(BaseDjangoAdminRoleForm, self).__init__(*args, **kwargs)
self.fields['user'].queryset = User.objects.exclude(...)
This has the advantage of evaluating the usernames every time the form is created - at the moment, they are only evaluated once when the server starts.

ImportError: No module named 'models' in Python 3

I have a new Python project, with a models.py file that looks like this:
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
class Metric(models.Model):
users = models.ManyToManyField(User, through = 'Vote')
name = models.CharField(max_length = 255)
class Vote(models.Model):
metric = models.ForeignKey(Metric, on_delete = models.CASCADE)
user = models.ForeignKey(User, on_delete = models.CASCADE)
rating = models.IntegerField(validators = [MinValueValidator(0), MaxValueValidator(10)])
email = models.EmailField
def __str__(self):
return str(self.rating)
and an admin.py file like this:
from django.contrib import admin
from models import Metric, Vote
admin.site.register(Metric)
admin.site.register(Vote)
When running this with Python 2.7.5, launching the app works fine. When I try to run it using Python 3.5.1, I get the error ImportError: No module named 'models', with this backtrace:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x103bd2b70>
Traceback (most recent call last):
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Users/sashacooper/pyenv/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/Users/sashacooper/pyenv/lib/python3.5/importlib/__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 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/Users/sashacooper/Desktop/pogroms/crockerometer2/crockerometer/admin.py", line 2, in <module>
from models import Metric, Vote
I've tried adding from __future__ import absolute_import to the start of the admin.py file per similarly titled Stack Overflow posts but it didn't change the error. What's causing it?
In Python 3 you must tell it when you are using relative imports:
from .models import ...
try from .models import Metric, Vote in your admin.py
I have always used:
from myapp.models import ...
Rather than a relative import. Just my personal preference. Perhaps relative import makes more sense if it is the admin.py for myapp, but I still like the explicitness of having the app name in the import.

NameError: name PositiveSmallIntegerField is not defined

Django 1.5 & Python 3.2.3, on Ubuntu 12.04.
Very odd error when trying to syncdb my DB. I've got some fields that don't look wrong but Django's spitting out this error message when I run python3 manage.py sqlall..
NameError: name 'PositiveSmallIntegerField' is not defined
Huh? I tried Googling this, but there's not a single thing about it anywhere. So I'm guessing I've made some stupid mistake but I can't see it. My models.py looks like this:
from django.db import models
class Song(models.Model):
own = models.BooleanField(default=True)
heard = models.DateTimeField(blank=True,null=True)
release_date = models.DateField(blank=True,null=True)
style = models.CharField(max_length=255,blank=True,null=True)
artist = models.CharField(max_length=255,blank=True,null=True)
featuring = models.CharField(max_length=255,blank=True,null=True)
title = models.CharField(max_length=255,blank=True,null=True)
listen = models.URLField(max_length=255,blank=True,null=True)
highest_chart_pos = models.PositiveSmallIntegerField()
note = models.TextField(blank=True,null=True)
That's all there is to it, and I copy-n-pasted PositiveSmallIntegerField straight from the Django documentation so I know there isn't a typo in it that I'm overlooking. So, how is PositiveSmallIntegerField not defined?
Throwing this in here because I found myself with the same error, creating a model for a
song, too!
from django.db import models
class Track(models.Model):
release = models.ForeignKey('Release', on_delete=models.CASCADE)
position = models.PositiveSmallIntegerField()
number = PositiveSmallIntegerField()
name = models.CharField(max_length=100)
length = models.DurationField()
There is a slight difference, here. I left out the namespace of models. before my PositiveSmallIntegerField. It looks like you didn't do that, above, but maybe someone else with a similar error will made my mistake, too.
Here was my stacktrace:
(env) Cam#cambook:~/Sites/juke% python manage.py makemigrations playlists
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
django.setup()
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Cam/Sites/juke/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/Users/Cam/Sites/juke/env/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.5_1/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/Cam/Sites/juke/playlists/models.py", line 60, in <module>
class Track(models.Model):
File "/Users/Cam/Sites/juke/playlists/models.py", line 63, in Track
number = PositiveSmallIntegerField()
NameError: name 'PositiveSmallIntegerField' is not defined