I'm trying to add a new database model that will let me "group" expenses, but am running across this issue when running python manage.py makemigrations
My virtual environment looks like this:
Django==1.7.3
argparse==1.2.1
django-braces==1.4.0
django-chartit==0.1
django-crispy-forms==1.4.0
django-debug-toolbar==1.2.2
psycopg2==2.6
six==1.9.0
sqlparse==0.1.14
wsgiref==0.1.2
Here is the traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 111, in handle
convert_apps=app_labels or None,
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 42, in changes
changes = self._detect_changes(convert_apps, graph)
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 109, in _detect_changes
self.old_apps = self.from_state.render(ignore_swappable=True)
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 67, in render
model.render(self.apps)
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 316, in render
body,
File "/home/jeff/.virtualenvs/ggc/local/lib/python2.7/site-packages/django/db/models/base.py", line 229, in __new__
'base class %r' % (field.name, name, base.__name__)
django.core.exceptions.FieldError: Local field u'id' in class 'ExpenseGroup' clashes with field of similar name from base class 'Asset
'
This is the model code - I've tried cutting the ExpenseGroup model down to only the groupName as a field but I get the same error. What am I missing?
class Asset(TimeStampedModel):
assetName = models.CharField(max_length=255)
assetAddress = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, blank=True)
class Meta:
unique_together = ('assetName', 'assetAddress')
def __str__(self):
return self.assetName
def save(self, *args, **kwargs):
self.slug = slugify(self.assetName)
super(Asset, self).save(*args, **kwargs)
class ExpenseGroup(TimeStampedModel):
groupName = models.CharField(max_length=255, blank=False)
expenseName = models.ForeignKey(Expense, related_name='expenseGroup')
class Meta:
unique_together = ('expenseName', 'groupName')
def __str__(self):
return self.groupName
def save(self, *args, **kwargs):
return super(ExpenseGroup, self).save(*args, **kwargs)
class Expense(TimeStampedModel):
assetName = models.ForeignKey(Asset, related_name='assetExpense')
category = models.ForeignKey(ExpenseCategory, related_name='expenseCategory')
expensePeriod = models.DateTimeField(blank=False)
expenseName = models.CharField(max_length=255, blank=False)
expenseAmount = models.DecimalField(max_digits=20, decimal_places=2, blank=True)
class Meta:
unique_together = ('expenseName', 'expensePeriod')
def __str__(self):
return self.expenseName
def save(self, *args, **kwargs):
super(Expense, self).save(*args, **kwargs)
Can you post the TimeStampedModel definition? I suspect that you didn't declare the base model as Abstract. That why the "id" fields are conflicted with each others.
class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
It's a bug with Django 1.7.3, upgrade to the latest and you'll be fine (1.7.5 at the time)
There's more to this than what you posted. Can you post your entire models file? or a link to a gist? I'm surprised you are not getting an error about the FK reference to 'Expense' from the 'ExpenseGroup' model, as it's defined later in the file.
Do you have any existing migrations? I would suggest deleting any of your existing migrations and all your pyc files and trying again.
Related
Hey guys i have been trying to create an inline TabularInline view of the my model in the django admin.py file. I am facing an issue where i am getting the following error in the code below.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/brian/Desktop/django react learning /site/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/home/brian/Desktop/django react learning /site/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "/home/brian/Desktop/django react learning /site/lib/python3.8/site-packages/django/core/management/base.py", line 442, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'tweets.admin.TweetlikeAdmin'>: (admin.E202) 'tweets.Tweet' has no ForeignKey to 'tweets.Tweet'.
So at first I thought I had missed something but when I tried changing it I got more errors which really don't make sense. so I made sure I share with you my models.py file and my admin.py file
here is my models.py file
class Tweetlike(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
tweet = models.ForeignKey('Tweet',on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
class Tweet(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE) #this means that one user can own tweets
likes = models.ManyToManyField(User,related_name='tweet_user', blank=True, through=Tweetlike)
content = models.TextField(blank=True,null=True)
timestamp = models.DateTimeField(auto_now_add=True)
image = models.FileField(upload_to='images/',blank=True,null=True)
def __str__(self):
return self.content
and lastly here is the admin.py file. this is where the error is coming from when i tried running the server
class TweetlikeAdmin(admin.TabularInline):
model = Tweet
class TweetAdmin(admin.ModelAdmin):
inlines = [TweetlikeAdmin,]
list_display = ['__str__','user']
search_fields = ['content','user__username', 'user__email']
class Meta:
model = Tweet
admin.site.register(Tweet,TweetAdmin)
You've not set the correct model, you've got them both pointing at the Tweet model. Change the inline model;
class TweetlikeAdmin(admin.TabularInline):
model = Tweetlike
please help a beginner. I'm trying to build a poll app in Django and I want to change my admin panel so that I can change and add questions and choices in the same page iv already tried to create a new model and bind the question and choice model together but didn't work please help me.
this is my models.py inside my poll app and another problem I have is that I want to have different numbers of choices for different questions but I don't know how to write
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Bind(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
add_question =Question(question_text=question_text,pub_date=pub_date)
choice_text_1= models.CharField(max_length=200,default='yes')
votes_1= models.IntegerField(default=0)
choice_text_2= models.CharField(max_length=200,default='yes')
votes_2= models.IntegerField(default=0)
choice_text_3= models.CharField(max_length=200,default='yes')
votes_3= models.IntegerField(default=0)
choice_text_4= models.CharField(max_length=200,default='yes')
votes_4= models.IntegerField(default=0)
add_choice1=Choice(choice_text=choice_text_1,votes=votes_1)
add_choice2=Choice(choice_text=choice_text_2,votes=votes_2)
add_choice3=Choice(choice_text=choice_text_3,votes=votes_3)
add_choice4=Choice(choice_text=choice_text_4,votes=votes_4)
def __str__(self):
return self.question_text
return self.choice_text
and this is my admin panel id like to change it that I can add question with different number of choices and when I save I can find save question in question model pannel and choices in the choice model panel please help me I'm a beginner
enter image description here
and this is views.py file:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {'question': question,'error_message': "You didn't select a choice.",})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
and the error by executing the python manage.py migrate
C:\projects\AM\FM\mysite>python manage.py migrate Operations to
perform: Apply all migrations: admin, auth, contenttypes, polls,
sessions Running migrations: Applying
polls.0009_auto_20200914_1002...Traceback (most recent call last):
File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init_.py",
line 1774, in get_prep_value
return int(value) ValueError: invalid literal for int() with base 10: 'choice'
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 22, in
main() File "manage.py", line 18, in main
execute_from_command_line(sys.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py",
line 401, in execute_from_command_line
utility.execute() File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py",
line 371, in execute
output = self.handle(*args, **options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py",
line 85, in wrapped
res = handle_func(*args, **kwargs) File "C:\projects\AM\FM\lib\site-packages\django\core\management\commands\migrate.py",
line 243, in handle
post_migrate_state = executor.migrate( File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py",
line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File
"C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py",
line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File
"C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py",
line 227, in apply_migration
state = migration.apply(state, schema_editor) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\migration.py",
line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File
"C:\projects\AM\FM\lib\site-packages\django\db\migrations\operations\fields.py",
line 104, in database_forwards
schema_editor.add_field( File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py",
line 328, in add_field
self.remake_table(model, create_field=field) File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py",
line 189, in remake_table
self.effective_default(create_field) File "C:\projects\AM\FM\lib\site-packages\django\db\backends\base\schema.py",
line 303, in effective_default
return field.get_db_prep_save(self.effective_default(field), self.connection) File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields\related.py",
line 971, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection) File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py",
line 823, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False) File
"C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py",
line 2388, in get_db_prep_value
value = self.get_prep_value(value) File "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py",
line 1776, in get_prep_value
raise e.class( ValueError: Field 'id' expected a number but got 'choice'.
You cannot directly assign other models to other model's fields. You have to use either ForeignKey (One Object To Many Referrable Objects) or ManyToManyField (Many Objects Can Be Contained To This Object).
At this point, you might want to consider making class Bind to class Questionnaire since you're combining them.
With that, with fixes applied and redundancies, this should be the final code (for inheritances only!)
class Question(models.Model):
question_text = models.CharField(max_length=200)
question_choices = models.ForeignKey("Choice", on_delete=models.CASCADE)
pub_date = models.DateTimeField(help_text='date published', auto_now_add=True)
def __str__(self):
return self.question_text
# No need to refer to the `Question` Model unless you have something to do important.
# Cross-Reference is okay, but its redundant unless special handling is required (for instance, you want pure integrity of ownership of this object, etc. But its quite hard to manage if your models were scaling.)
class Choice(models.Model):
# question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Questionnaire(models.Model):
questions = models.ManyToManyField("Question", blank=True)
pub_date = models.DateTimeField(help_text='date published', auto_now_add=True)
def __str__(self):
return self.question_text
NOTES:
If you read the changes closely, you might see yourself, why I assigned the object in "str" form? That's because Django was able to load objects, even or after the one who requires it. Meaning, You don't need to put another object on the top to refer at, but rather, just put it in str reference even the object is placed anywhere and you're good to go.
Note that in DateTimeField, you would want to consider auto_now_add=True, it automatically handles the time where this object has been saved for the first time.
I want to make all choices under Question. This would be nice because if you want to make a question, there's a field available for you to create a choice to.
I changed Bind with Questionnaire for clarity. This should be enough to see the relationship or inheritance to your model.
I used ManyToManyField to set number of questions (or objects) to this Questionnaire.
Usually, in such cases, you don't need to create "Bind" model. You just need to add "sequence" integer field into your Choice model. Then, each question can have infinite number of choices, for example:
Choice.objects.create(question=question1, sequence=0)
Choice.objects.create(question=question1, sequence=1)
Choice.objects.create(question=question1, sequence=2)...
I am trying to make a description to every user, in my new project. But i get an error when i try to makemigrations. I do not know how to fix it.
I have tried different things but nothing worked, my coding is maybe very bad, but i am also new to python and django.
The Error:
C:\Users\bruger\Dropbox\min-login-web\web_login>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\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 143, in handle
loader.project_state(),
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\loader.py", line 322, in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\graph.py", line 378, in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\migration.py", line 87, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\operations\models.py", line 85, in state_forwards
list(self.managers),
File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\state.py", line 377, in __init__
if field.is_relation and hasattr(field.related_model, '_meta'):
AttributeError: 'CharField' object has no attribute 'is_relation'
My Models file:
from django import forms
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
class Desc(models.Model):
description = forms.CharField(widget = forms.Textarea, max_length = 250, required=False)
def __str__(self):
return f'{self.user.username} Desc'
I Hope somebody can help me, because this is really getting on my nerves.
You mixed forms and models. A model does not specify a (HTML) form, it specifies how the database should store data, so you need to use a models.CharField:
class Desc(models.Model):
description = models.CharField(max_length=250)
Such CharField has no widget assigned to it, this is something you should handle at the form level.
You probably will need to make migrations, since up to this point, there was no description field in your Desc model.
I agree to some extent that it is confusing that the forms have frequently a field with the same name (well those typically are the default form fields for the model field with the same name). The idea is however that model fields specify the columns in a database, whereas form fields specify text boxes, check boxes, etc. in a (HTML) form.
I create CustomUser class that extends AbstractUser, and add a ForeignKey field that reference to City Model
class City(models.Model):
created_dt = models.DateTimeField("Created Time", auto_now_add=True)
code = models.CharField(max_length=64, unique=True)
name = models.CharField(max_length=64)
class CustomUser(AbstractUser):
city = models.ForeignKey(City)
REQUIRED_FIELDS = ['city']
I add the CustomUser to setting:
AUTH_USER_MODEL = "myapp.CustomUser"
When I tried to syncdb, it prompted me to create super user, when I fill in the city, I got this error:
City: 1
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 116, in handle
user_data[field_name] = field.clean(raw_value, None)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 255, in clean
self.validate(value, model_instance)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1201, in validate
using = router.db_for_read(model_instance.__class__, instance=model_instance)
File "/var/www/uib_webservice/.virt1/local/lib/python2.7/site-packages/django/db/utils.py", line 250, in _route_db
return hints['instance']._state.db or DEFAULT_DB_ALIAS
AttributeError: 'NoneType' object has no attribute '_state'
can someone explain to me why ?
I'm still a newbie in django, thanks
You can't set a required field to be a foreign key according to the docs. There's a ticket open with something similar to what you're encountering. I'd suggest subclassing CustomUserManager and override the create_superuser method on it, then use it for the objects manager on your CustomUser model.
I am trying to extend the user model using AbstractUser component. But I haven't been successful on this. After reseraching lot I wrote my model Employee(Extended user model) but now I get the below error when I do syncdb.
If anyone can help me by suggesting or running my models.py that would be great. when I run syncdb it asks superuser creation after i give the credentials I get a below error.
Error : (Complete traceback is pasted after the models.py)
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: epi_employee.emp_id may not be NULL
My models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
# Create your models here.
class Employee(AbstractUser):
emp_id = models.IntegerField('Employee Id', max_length=5,unique=True)
dob = models.DateField('Date of Birth', null=True,blank=True)
def __unicode__(self):
return self.get_full_name
class Department(models.Model):
name = models.CharField('Department Name',max_length=30, unique=True,default=0)
def __unicode__(self):
return self.name
class Report(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
dept = models.ForeignKey(Department, verbose_name="Department")
report1 = models.ForeignKey(Employee,null=True,blank=True, verbose_name=u'Primary Supervisor',related_name='Primary')
report2 = models.ForeignKey(Employee,null=True,blank=True, verbose_name=u'Secondary Supervisor',related_name='Secondary')
def __unicode__(self):
return self.user
def upload_to(instance, filename):
return 'images/%s/%s' % (instance.user.username, filename)
class thumbnail((models.Model)):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
image = models.ImageField('Profile Pic',null=True, blank=True, upload_to=upload_to)
def __unicode__(self):
return self.user
class Passport(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
passport = models.CharField('Passport Number',max_length=15)
passportissue = models.CharField('Issuing City',max_length=15, default='Bangalore')
passportcountry = models.CharField('Issuing City',max_length=15, default='India')
passportstart = models.DateField('Valid From', null=True,blank=True)
passportend = models.DateField('Valid Till', null=True,blank=True)
def __unicode__(self):
return self.user
class CurrentAddress(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
address = models.TextField('Current Address')
city = models.CharField('City', max_length=20, default = 'Bangalore')
state = models.CharField('State', max_length=20, default= 'Karnataka')
country = models.CharField('Country', max_length=20, default = 'India')
mobile1 = models.IntegerField('Mobile1',max_length=12)
mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
email = models.EmailField('Personal Email Id', blank=True)
def __unicode__(self):
return self.user
COMPLETE TRACE BACK: Please find the complete error which I am getting. Let me know if more information required
(testenv1) F:\djangoenv\testenv1\employee>python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table django_content_type
Creating table django_session
Creating table epi_employee_groups
Creating table epi_employee_user_permissions
Creating table epi_employee
Creating table epi_department
Creating table epi_report
Creating table epi_thumbnail
Creating table epi_passport
Creating table epi_currentaddress
You just installed Django's auth system, which means you don't have any superuse
rs defined.
Would you like to create one now? (yes/no): yes
Username: admin
Email address: admin#admin.com
Password:
Password (again):
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\__init__.
py", line 399, in execute_from_command_line
utility.execute()
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\__init__.
py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 285, in execute
output = self.handle(*args, **options)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 415, in handle
return self.handle_noargs(**options)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\commands\
syncdb.py", line 112, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive, db)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\sql.py",
line 216, in emit_post_sync_signal
interactive=interactive, db=db)
File "F:\djangoenv\testenv1\lib\site-packages\django\dispatch\dispatcher.py",
line 185, in send
response = receiver(signal=self, sender=sender, **named)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\management\_
_init__.py", line 126, in create_superuser
call_command("createsuperuser", interactive=True, database=db)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\__init__.
py", line 159, in call_command
return klass.execute(*args, **defaults)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 285, in execute
output = self.handle(*args, **options)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\management\c
ommands\createsuperuser.py", line 141, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user
_data)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\models.py",
line 195, in create_superuser
**extra_fields)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\models.py",
line 186, in _create_user
user.save(using=self._db)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
545, in save
force_update=force_update, update_fields=update_fields)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, upda
te_fields)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
654, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
687, in _do_insert
using=using, raw=raw)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\manager.py", li
ne 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\query.py", line
1511, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\sql\compiler.py
", line 898, in execute_sql
cursor.execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\util.py", lin
e 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\util.py", lin
e 53, in execute
return self.cursor.execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\utils.py", line 99, in
__exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\util.py", lin
e 53, in execute
return self.cursor.execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\sqlite3\base.
py", line 450, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: epi_employee.emp_id may not be NULL
You defined emp_id as unique but not nullable, you can add null=True to the model,but seems to be that you wanna use emp_id as a primari_key, so to ensure that the field can not be null and must be unique you maybe wanna use a models.AutoField:
emp_id = models.AutoField(primary_key=True)
this guarantee that the field is unique an can not be null.
Now, for the max_length property and the model's name (Employee) I think that emp_id will be a number that the company gives you, for example my id in the company where I work is 0001544, so to avoid that problem you can create a custom manager:
from django.contrib.auth.models import BaseUserManager
class EmployeManager(BaseUserManager):
def create_user(self, username, email,emp_id, password=None):
if not username:
raise ValueError('Employers must have an username.')
if not email:
raise ValueError('Employers must have an email address.')
if not emp_id:
raise ValueError('Employers must have an employer id')
user = self.model(username=username, email=self.normalize_email(email), emp_id=emp_id)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, emp_id, password):
user = self.create_user(username, email, emp_id, password)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
and then in the models file add this:
from myapp.managers import EmployeManager
and into your Employers Model ass this
objects = EmployeManager()
then you run python manage.py syncdb
hope this helps you, any doubt, tell me.
You defined emp_id unique but not nullable.
So when you created the superuser, django raises that emp_id can't be null.
If you want it as primary key remove that field.
If you want define it later put in emp_id field null=True
Anyway you can read here https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields
P.s. I see another error:
self.get_full_name()
But this is the super behaviour so you could delete it at all.