Cannot run django server after integrating database - django

I am having problems running my server after I try to integrate the database with the application using the "python manage.py inspectdb > /models.py" command.
This is what I have in my models.py file
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database.
from __future__ import unicode_literals
from django.db import models
class AuthGroup(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=80)
class Meta:
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
id = models.IntegerField(primary_key=True)
group = models.ForeignKey(AuthGroup)
permission = models.ForeignKey('AuthPermission')
class Meta:
db_table = 'auth_group_permissions'
class AuthPermission(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
content_type = models.ForeignKey('DjangoContentType')
codename = models.CharField(max_length=100)
class Meta:
db_table = 'auth_permission'
class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
password = models.CharField(max_length=128)
last_login = models.DateTimeField()
is_superuser = models.BooleanField()
username = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=75)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
db_table = 'auth_user'
class AuthUserGroups(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
group = models.ForeignKey(AuthGroup)
class Meta:
db_table = 'auth_user_groups'
class AuthUserUserPermissions(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
permission = models.ForeignKey(AuthPermission)
class Meta:
db_table = 'auth_user_user_permissions'
class DjangoContentType(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
db_table = 'django_content_type'
class DjangoSession(models.Model):
session_key = models.CharField(max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
db_table = 'django_session'
class DjangoSite(models.Model):
id = models.IntegerField(primary_key=True)
domain = models.CharField(max_length=100)
name = models.CharField(max_length=50)
class Meta:
db_table = 'django_site'
class DjangoUser(models.Model):
firstname = models.CharField(max_length=256)
lastname = models.CharField(max_length=256)
username = models.CharField(primary_key=True, max_length=256)
password = models.CharField(max_length=256)
class Meta:
db_table = 'django_user'
and this is the error message I get
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.comma
nds.runserver.Command object at 0x0000000002CD1518>>
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\django\core\management\commands\runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "C:\Python33\lib\site-packages\django\core\management\base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python33\lib\site-packages\django\core\management\validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 166, in get_app_errors
self._populate()
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 72, in _populate
self.load_app(app_name, True)
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "C:\Python33\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
TypeError: source code string cannot contain null bytes
It seems I have a null variable some place but I don't know where that is coming from. I would appreciate some help.

I just had this problem myself. I finally fixed it:
open the generated model.py file in Notepad++ (or other)
copy/paste the generated code into a new file in IDLE
Save over model.py
I'm not sure why this works, but I got an encoding error trying to open the file directly in IDLE. So I copy/pasted the code, and it fixes everything.

I had the same problem using Sublime 3 as editor. It got solved if I resaved the models.py file in my app folder as 'Save with Encoding :: UTF-8'.

Related

AttributeError: 'str' object has no attribute '_meta' when attempting to use Many to Many field on self with through model - Django

Django version - 4.0.4
I am making a recipe engine website and I am trying to create a table Ingredient where each ingredient may have substitutable ingredients.
For example, ingredient "acorn squash" has the following substituable ingredients:
ingredient title: butternut squash. Conversion: 1 cup acorn squash = 1 cup butternut squash
ingredient title: pumpkin. Conversion: 1 cup acorn squash = 1 cup pumpkin
To achieve this, I have a class Ingredient and a class SubstitutableIngredient in models.py. I use a many to many field in Ingredient which uses "through" to link to the SubstitutableIngredient table, as I have extra fields such as "conversion". I use 'self' as a substitutable ingredient is still an ingredient. When attempting to makemigrations or migrate, I get the following error: AttributeError: 'str' object has no attribute '_meta' when attempting to makemigrations or migrate. Stack trace shown further below.
My code in Models.py is:
from django.db import models
# Create your models here.
class Ingredient(models.Model):
title = models.CharField(max_length=200,
unique=True) # unique field. There may only be one ingredient in the database with the same title.
# many to many field
substitutableIngredients = models.ManyToManyField(
'self',
through='SubstitutableIngredient',
through_fields=('originalIngredient', 'newIngredient'),
)
def __str__(self):
return self.title
class SubstitutableIngredient:
originalIngredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name="originalIngredient")
newIngredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name="newIngredient")
# the conversion rules between the ingredients (e.g. 1 cup = 2 cups)
conversion = models.CharField(max_length=200)
# A Cuisine has a title which is unique.
class Cuisine(models.Model):
title = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.title
# recipe class inherits from Model
class Recipe(models.Model):
# attributes
title = models.CharField(max_length=200)
# every Recipe can have many ingredients and each ingredient can have many recipes.
# relationship is modelled by the IngredientInRecipe model.
ingredients = models.ManyToManyField(
Ingredient,
through='IngredientInRecipe',
through_fields=('recipe', 'ingredient')
)
instructions = models.TextField(blank=True, null=True)
vegetarian = models.BooleanField(blank=True, null=True)
vegan = models.BooleanField(blank=True, null=True)
glutenFree = models.BooleanField(blank=True, null=True)
dairyFree = models.BooleanField(blank=True, null=True)
sourceUrl = models.CharField(max_length=200, blank=True, null=True)
image = models.CharField(max_length=200, blank=True, null=True)
cuisines = models.ManyToManyField(Cuisine, blank=True, null=True)
def __str__(self):
return self.title
# Intermediary class working between Recipe and Ingredient.
class IngredientInRecipe(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
unit = models.CharField(max_length=200)
quantity = models.FloatField()
def __str__(self):
return self.recipe.title + "," + self.ingredient.title
Strack trace:
C:\[pathname]>python manage.py makemigrations
Traceback (most recent call last):
File "C:[pathname]\manage.py", line 22, in <module>
main()
File "C:[pathname]\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 455, in execute
self.check()
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 487, in check
all_issues = checks.run_checks(
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\model_checks.py", line 36, in check_all_models
errors.extend(model.check(**kwargs))
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 1442, in check
*cls._check_fields(**kwargs),
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 1556, in _check_fields
errors.extend(field.check(from_model=cls, **kwargs))
File "C:\[pathname]\lesle\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 1376, in check
*self._check_relationship_model(**kwargs),
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 1603, in _check_relationship_model
for f in through._meta.fields:
AttributeError: 'str' object has no attribute '_meta'
I'm very confused because the following code, which is almost identical to mine, works perfectly fine.
Example code:
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=50)
# note the additional arguments here
friends = models.ManyToManyField(
'self',
# recursive relationships to self with intermediary
# through model are always defined as non-symmetrical
# symmetrical=False,
through='PersonFriend',
# this argument is required to define a custom
# through model for many to many relationship to self
# position matters: 1 - source (from), 2 - target (to)
through_fields=('person', 'friend'),
)
class PersonFriend(models.Model):
# required relationship-defining foreign keys
# (note that the order does not matter, it matters
# in 'through_fields' argument in 'friends' field of the 'Person' model)
person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="person")
friend = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="friend")
# additional fields
comment = models.CharField(max_length=50)
What I've already tried:
Deleting the database and migrations files
changing to through=main.SubstituableIngredient as suggested in Django many-to-many 'str' object has no attribute '_meta' does not help

Django import export, get() returned more than one

Please help me to find a solution to this error, whene using django-import-export
here is my code :
Models :
class ChartOfAccounts(models.Model):
code = models.CharField('code plan comptable', max_length=20, unique=True)
name = models.CharField('plan comptable', max_length=100)
def __str__(self):
return self.code
class Company(models.Model):
code = models.CharField('code société', max_length=20, unique=True)
name = models.CharField('société', max_length=100)
addr = models.CharField('adresse', max_length=100, blank=True, null=True)
chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable')
def __str__(self):
return self.code
class GLAccount(models.Model):
class Meta:
unique_together = (('code', 'chart_of_accounts'),)
code = models.CharField('code compte comptable', max_length=10)
chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable')
name = models.CharField('compte comptable', max_length=100, help_text='text descriptif du compte comptable')
def __str__(self):
return f'{self.code}, {self.chart_of_accounts}'
class CompanyAccount(models.Model):
company = models.ForeignKey(Company, verbose_name='code société', on_delete=models.CASCADE)
gl_account = models.ForeignKey(GLAccount, verbose_name='compte comptable', on_delete=models.CASCADE)
Resources :
class CompanyAccountResource(ModelResource):
class Meta:
model = models.CompanyAccount
fields = ('company', 'gl_account',)
exclude = ('id',)
import_id_fields = ('company', 'gl_account',)
skip_unchanged = False
report_skipped = False
# fields
company = Field(
column_name=Meta.model._meta.get_field('company').verbose_name,
attribute='company',
widget=ForeignKeyWidget(models.Company, field='code')
)
gl_account = Field(
column_name=Meta.model._meta.get_field('gl_account').verbose_name,
attribute='gl_account',
widget=ForeignKeyWidget(models.GLAccount, field='code')
)
def get_export_order(self):
export_fields = ['company', 'gl_account', ]
return export_fields
My data is :
Company model data here
ChatOfAccounts model data here
GLAccount model data here
CompanyAccountResource Excel canvas to import data
the problem :
a GLAccount code may apear in 2 chart of accounts, each related to one company, and when try to import data from excel to CompanyAccountResource, the error below will apear :
Line number: 1 - get() returned more than one GLAccount -- it returned 2!
S001, 600000
Traceback (most recent call last):
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\resources.py", line 639, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\resources.py", line 334, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\resources.py", line 327, in get_instance
return instance_loader.get_instance(row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\instance_loaders.py", line 29, in get_instance
params[field.attribute] = field.clean(row)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\fields.py", line 66, in clean
value = self.widget.clean(value, row=data)
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\import_export\widgets.py", line 396, in clean
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val})
File "C:\Users\Leo\PycharmProjects\Django\DjangoSnippets\venv\lib\site-packages\django\db\models\query.py", line 433, in get
raise self.model.MultipleObjectsReturned(
app1.models.GLAccount.MultipleObjectsReturned: get() returned more than one GLAccount -- it returned 2!
The error is occurring because you are defining import_id_fields which don't uniquely identify an object.
import_id_fields is used by the import workflow to identify an existing model instance for update. In your case, the combination of 'company', 'gl_account' is identifying multiple rows in the CompanyAccountResource.
If you need your import logic to update existing instances, then you will have to find a way to uniquely identify the row for update.

Django: error while trying to access ManyToMany field

I'm trying to create a twitter like application as a practice project, and following this video tutorial. I've created following models in my app.
class Profile(models.Model):
user = models.OneToOneField(to=User, on_delete=models.CASCADE)
bio = models.CharField(max_length=160, blank=True)
profile_photo = models.ImageField(blank=True, null=True)
followers = models.ManyToManyField("self", through="Relationship", related_name="follow_to",
symmetrical=False, blank=True)
class Relationship(models.Model):
user_followed = models.ForeignKey("User", related_name="followed", on_delete=models.CASCADE)
followed_by = models.ForeignKey("Profile", related_name="follower", on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
The migrations ran successfully.
After this for testing, I created two users (user1 and user2) with their respective profiles and made user2 to follow user1. Here's the code for that-
Relationship.objects.create(user_followed=user1,followed_by=user2.profile)
This relationship was successfully created. I try the following code to try to get followers of user1-
user1.profile.followers.all()
But above code is giving following errors-
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 535, in __get__
return self.related_manager_cls(instance)
File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 821, in __init__
self.target_field_name = rel.field.m2m_reverse_field_name()
File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1554, in _get_m2m_reverse_attr
return getattr(self, cache_attr)
AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'
I tried following the method mentioned here, but it is also giving the same error. I'm not sure where have I committed a mistake. I would be thankful if someone can correct me.
Since you make an ManyToManyField to 'self' both the ForeignKeys should point to Profile:
class Relationship(models.Model):
followed = models.ForeignKey(
'Profile',
related_name='followed',
on_delete=models.CASCADE
)
followed_by = models.ForeignKey(
'Profile',
related_name='follower',
on_delete=models.CASCADE
)
timestamp = models.DateTimeField(auto_now=True)
Since now both ForeignKeys point to the same model, there is an ambiguity what the source field, and what the target field is. You resolve this by specifying this with the through_fields=… parameter [Django-doc]:
class Profile(models.Model):
user = models.OneToOneField(to=User, on_delete=models.CASCADE)
bio = models.CharField(max_length=160, blank=True)
profile_photo = models.ImageField(blank=True, null=True)
followers = models.ManyToManyField(
'self',
through='Relationship',
related_name='follow_to',
related_fields=('followed', 'followed_by')
symmetrical=False,
blank=True
)
You thus can create a follower Relation with:
Relationship.objects.create(
followed=user1.profile,
followed_by=user2.profile
)

Can't add object to Django's Many-To-Many Field

I'm trying to make app with Many-To-Many Field. And I write it and wont to try it. So, I started shell and make some objects and I get this error.
>>> mzz.controlsOrganization.add(org1, org2)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/fdobrovolny/virtualenv/first/lib/python2.7/site-packages/django/db/models/fields/related.py", line 848, in __get__
through=self.field.rel.through,
File "/home/fdobrovolny/virtualenv/first/lib/python2.7/site-packages/django/db/models/fields/related.py", line 538, in __init__
(instance, source_field_name))
ValueError: "<MZZ: TEST 1>" needs to have a value for field "mzz" before this many-to-many relationship can be used.
MZZ class:
class MZZ(models.Model):
name = models.CharField(max_length=100)
name.short_decription = u'Název MZZ'
ident = models.CharField(max_length=45, unique=True)
active = models.BooleanField()
active.boolean = True
kind = models.ForeignKey(kind)
deliveryDate = models.DateField()
stateAfterDelivery = models.CharField(max_length=200)
dateOfCommissioning = models.DateField()
prescribedParameters = models.CharField(max_length=200)
responsibleStaff = models.ForeignKey(User)
dateOfManufacture = models.DateField()
manufacturer = models.ForeignKey(organization, related_name='manufacturer')
type = models.CharField(max_length=50)
serialNumber = models.CharField(max_length=80)
frequencyOfControls = models.ForeignKey(controls_frequency)
location = models.CharField(max_length=50)
methodOfControls = models.CharField(max_length=100)
controlsOrganization = models.ManyToManyField(organization, related_name='controlsOrganization')
servisOrganization = models.ManyToManyField(organization, related_name='servisOrganization')
def __unicode__(self):
return self.name'
organization class:
class organization(models.Model):
name = models.CharField(max_length=200)
adress = models.CharField(max_length=200)
telephoneNumber = models.CharField(max_length=35)
email = models.EmailField()
def __unicode__(self):
return self.name
Can please somebody help me?
You have to create the MZZ object and save() it first and then add an organization.
mzz = MZZ() # create
mzz.save() # save()
o = organization()
o.save()
m.organization.add(o) # add(o)
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

django custom command complains AssertionError: ForeignKey(None) is invalid. why

I've followed django custom command tutorial, the link is here.
My working directory looks like this:
myapps/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
my_command.py
tests.py
views.py
My code looks like this:
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def handle(self, *args, **options):
print '=========='
self.stdout.write('Successfully closed poll ttt')
When I run the command manage.py my_command, I got the following errors,
File "D:/ERP\apps\person\salary\models.py", line 8, in <module>
class Salarys(models.Model):
File "D:/ERP\apps\person\salary\models.py", line 14, in Salarys
Unit = models.ForeignKey(Units, verbose_name = u'def_unit, on_delete = models.PROTECT)
File "D:\Python27\Lib\site-packages\django\db\models\fields\related.py", line 910, in __init__
assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
Obviously, the first parameter of ForeignKey is my model Units, how do I silence the compiler's complaint?
ps: my model looks like this:
my model looks like this now.
class Salarys(models.Model):
'''
describe : salary table
author : liyang 2013-1-23
'''
User = models.ForeignKey(Users, verbose_name = u'account', on_delete = models.PROTECT)
Unit = models.ForeignKey(Units, verbose_name = u'def_unit', on_delete = models.PROTECT, null=True)
yy = models.IntegerField(u'year)
mm = models.IntegerField(u'month')
class Meta:
db_table = 'users_salarys'
class Units(models.Model):
'''
describe : def unit model
author : liyang 2012-12-4 11:45
'''
name = models.CharField(u'name',max_length = 20)
cname = models.CharField(u'company name',max_length = 20, blank = True, null = True)
aname = models.CharField(u'company short cut',max_length = 20, blank = True, null = True)
telephone = models.CharField(u'contact',max_length = 20, blank = True, null = True)
website = models.CharField(u'website',max_length = 25, blank = True, null = True)
address = models.CharField(u'address',max_length = 50, blank = True, null = True)
class Meta:
db_table = 'units'
....
the strange things are
1: User foreignkey does not make any troubles while Unit does...
2: my web server can be run without any problem while the command line can not be run...
Your class Units should come before your class Salarys:
class Units(models.Model):
...
class Salarys(models.Model):
user = models.ForeignKey(Users, verbose_name = u'account', on_delete = models.PROTECT)
unit = models.ForeignKey(Units, verbose_name = u'def_unit', on_delete = models.PROTECT, null=True)
One more recommendation: it's a best practice to name your model in singular. Django will automatically "pluralize" them. If Django fails to pluralize the class name properly, you can specify your own plural by adding the following to the models Meta:
class Meta:
verbose_name_plural = "salaries"