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

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"

Related

Django: Server Error (500) when trying to add an instance of a model

When I go on localhost:8000/admin and click on "Quotes +ADD" it shows me error 500 instead of the editing interface. "Posts" works well. I just want to know if, without seeing the code, you could just tell me the different possible sources of this problem ?
EDIT: Here are models.py and admin.py:
models.py
class TimestampedModel(models.Model):
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
class Meta:
abstract = True
# Create your models here.
class Post(TimestampedModel):
title = models.CharField(max_length = 255, default='')
intro = models.TextField(default='')
title_one = models.TextField(default='')
text_one = models.TextField(default='')
title_two = models.TextField(default='')
text_two = models.TextField(default='')
title_three = models.TextField(default='')
text_three = models.TextField(default='')
def __repr__(self):
return self.title
class Quote(models.Model):
quote = models.TextField(default='')
author = models.CharField(max_length = 60, default='')
def __repr__(self):
return self.quote
admin.py
from django.contrib import admin
from .models import Post, Quote
# Register your models here.
admin.site.register(Post)
admin.site.register(Quote)
I also would like to let you know that when I try to make migrations and then migrate, it says "No changes detected".
ProgrammingError at /admin/blog/quote/
relation "blog_quote" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_quote"
I'll guess it might be OperationalError due to not running migrations for Quotes model.
Providing models.py and admin.py contents would make it much easier to debug though.

when upgrading to django 1.4 I get 'X' has a relation with model 'Y', which has either not been installed or is abstract

I am updrading from django 1.3.1 which had no prolems, adter the upgrade to 1.4
I get this error message :
exome_project.phen_form_choice: 'term' has a relation with model "class 'exome_project.models.Term'", which has either not been installed or is abstract.
The strange thing is that the Term class that is supposedly abstract or missing is
defined right above it in the same python file :
class Term(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=600)
is_obsolete = models.IntegerField()
is_root = models.IntegerField()
subontology = models.CharField(max_length=3)
comment = models.TextField(blank=True)
acc = models.CharField(max_length=30)
def __unicode__(self):
return u'%s, Sub: %s' % (self.name, self.subontology)
class Meta:
db_table = u'v_term'
ordering = ['name','id']
app_label = 'HPO Views'
class phen_form_choice(models.Model):
term = models.OneToOneField(Term, primary_key=True)
phen_form_cat = models.ForeignKey('phen_form_category')
display_order = models.IntegerField()
def __unicode__(self):
#return u'Term Id: %s, Term Name: %s, Display Order: %s' % (self.term.name, self.phen_form_cat, self.display_order)
return self.term.name
class Meta:
ordering = ['phen_form_cat','display_order']
I think (not sure) it could be because of the app_label attribute in the Term class.
If both classes are in the same models.py file (it seems to be), you could try to remove the app_label = 'HPO Views' line. Or if both file are not in models.py, add this line to the other class.
Then use syncdb command. If it still doesn't work and you have a dev environement, try to tally delete de database then rebuild it with syncdb.
about app-label: https://docs.djangoproject.com/en/dev/ref/models/options/#app-label

Cannot run django server after integrating database

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'.

Auto populate DateTimeField not working in django forms

I am getting below error when I use auto_now_add in my Model Form.
TypeError: __init__() got an unexpected keyword argument 'auto_now_add'
Here is my model field
modified = models.DateTimeField(blank = True)
Declaration in form. I have seen in one of the posts DateTimeField Not Working
to add initial = datetime.datetime.now for auto populating
import datetime
modified = forms.DateTimeField(initial = datetime.datetime.now) - When I use this no error is coming but datetime was not auto populating.
I have used the same in self.fields['modified'] - Still no use
Any of the above statements were not working. Some one help me on this.
I am pasting all my model class and Model Form here
Model Class
class Users(models.Model):
name = models.CharField(max_length = 100)
role = models.ForeignKey(RolesConfig, db_column = 'role')
level = models.ForeignKey(LevelConfig, db_column = 'level')
team_name = models.ForeignKey(TeamNamesConfig, db_column = 'team_name')
location = models.ForeignKey(LocationConfig, db_column = 'location')
modified = models.DateTimeField(blank = True)
class Meta:
db_table = u'users'
def __str__(self):
return "%s" % (self.ldap)
def __unicode__(self):
return u'%s' % (self.ldap)
I have modified the field in phpmyadmin
This is my ModelForm
class TargetForm(forms.ModelForm):
modified = forms DateTimeField(initial = datetime.datetime.now)
def __init__(self, *args, **kwargs):
super(MMPodTargetForm, self).__init__(*args, **kwargs)
self.fields['modified'] = forms.DateTimeField(initial = datetime.datetime.now)
class Meta:
model = models.Users
I need to get current date and time autopopulated in the form, when the form loads. Tell me whats wrong in my code.
I think the error is because you're adding the auto_now_add extra argument to your form instead of to your mode. Try changing your model to the following to see if that fixes the problem (untested):
class Users(models.Model):
name = models.CharField(max_length = 100)
role = models.ForeignKey(RolesConfig, db_column = 'role')
level = models.ForeignKey(LevelConfig, db_column = 'level')
team_name = models.ForeignKey(TeamNamesConfig, db_column = 'team_name')
location = models.ForeignKey(LocationConfig, db_column = 'location')
modified = models.DateTimeField(auto_now = True)
class Meta:
db_table = u'users'
def __str__(self):
return "%s" % (self.ldap)
def __unicode__(self):
return u'%s' % (self.ldap)

django display content of a manytomanyfield

I started using django framework just a few days ago and i desperately need some help with my application.
It consists of client,project,admin,and admin payment classes where the admin_payment holds the ids of the admins and projects among other stuff.
My question is how i can display the "administrator's name" of each "project" in my admin listing of projects? the project class itself does not hold the administrator ids (the Admin_Payment does)
Currently i have the following structure: (striped down)
models.py
class Admin(models.Model):
admin_name = models.CharField(unique = True, blank = False, null = False, max_length = 128, verbose_name = u'admin full name')
def __unicode__(self):
return self.admin_name
class Meta:
ordering = ('id',)
verbose_name = u'Admin Info'
class Project(models.Model):
client = models.ForeignKey(Client, verbose_name = u'Client')
description = models.ForeignKey(Description, verbose_name = u'project description')
admins = models.ManyToManyField(Admin, verbose_name = u'Administrators', through = 'Admin_Payment')
class Admin_Payment(models.Model):
admin = models.ForeignKey(Admin, verbose_name = u'Administrator')
project = models.ForeignKey(Project, verbose_name = u'project')
admin.py (striped down)
class AdminInline(admin.TabularInline):
model = Admin
class ProjectAdmin(admin.ModelAdmin):
radio_fields = {'position': admin.HORIZONTAL, 'solution': admin.HORIZONTAL}
inlines = [AdminInline, ]
list_display = ['client','description','admin_name']
Clients and Descriptions appear correctly in the project listing but the admin names are not
Any help is appreciated
(sorry if i posted anything that doesnt make sense , i am a newbie in python and django)
Displaying the contents of ManyToMany field isn't supported by default by django, because the database will be queried for each row of the results. You can display it yourself by adding a method to your Project-model:
class Project(models.Model):
....
def admin_names(self):
return ', '.join([a.admin_name for a in self.admins.all()])
admin_names.short_description = "Admin Names"
and put admin_names in your list_display fields!