Related
I have just started learning Django and stuck my self in very strange condition.
I have created my own CustomUser instead of available in django.contrib.auth.models for authentication purpose.
I am getting some error or problems all together ,while running the program,i am trying to post all of them bellow.
I know all of them are occurred due to some silly mistake which i am unable to figure out on my own
1) When ever i am trying to run python manage.py make migrations i am getting error as bellow:-
You are trying to add a non-nullable field 'password' to customusers without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
2) When using python manage.py runserver is worked fine and run a emulated server on my local computer.
Now when i am trying to access admin/ it shows me the following error**:-**
Internal Server Error: /admin/
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such column: loginsignup_customusers.password
Second after filling the signup form :-
Internal Server Error: /signup/
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Admin\PycharmProjects\ecommerceproject\loginsignup\views.py", line 11, in signup_view
fm.save()
File "C:\Users\Admin\PycharmProjects\ecommerceproject\loginsignup\forms.py", line 42, in save
user = CustomUserManager.objects.create_user(
AttributeError: type object 'CustomUserManager' has no attribute 'objects'
[11/Jun/2021 11:35:58] "POST /signup/ HTTP/1.1" 500 67683
Bellow i am posting CustomUser and CustomUserManager class :-
CustomUser:-
class CustomUsers(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=40, unique=True)
email = models.EmailField()
password1 = models.CharField(max_length=10, null=False)
objects = CustomUserManager()
USERNAME_FIELD = 'username'
CustomUserManager:-
class CustomUserManager(BaseUserManager):
def create_user(self, username, email, password, **other_fields):
email = email.normalize_email(email)
user = self.model(email=email, username=username, **other_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
You might have another migration file in the migration folder, which you should delete and then try to run makemigrations. See this
I've been trying to solve this error for a week now and I can't seem to figure out how to fix this error. No one else who is using this repository is having the same problem as I am (I am up to date with the origin), so it has to be some sort of local issue, but I can't figure out what it would be.
This happens everytime I try to run the django unit tests that we have written. There are no problems when I runserver or when I do migrations, only when testing:
python manage.py test
_______ERROR MESSAGE:_________
Liams-MBP:GrammieGram Liam2$ python manage.py test grams
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "auth_user" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 62, in handle
failures = test_runner.run_tests(test_labels)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/runner.py", line 601, in run_tests
old_config = self.setup_databases()
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/runner.py", line 546, in setup_databases
self.parallel, **kwargs
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/utils.py", line 187, in setup_databases
serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db
run_syncdb=True,
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 131, in call_command
return command.execute(*args, **defaults)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 173, in handle
self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 311, in sync_apps
self.stdout.write(" Running deferred SQL...\n")
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 93, in __exit__
self.execute(sql)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_user" does not exist
My grams/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import datetime
import uuid
from django.contrib.postgres.fields import ArrayField
from django.db.models.signals import post_save
from django.dispatch import receiver
"""
#brief A class that describes a user profile.
#field user - the username of the user
#field usertype - the type of user profile (sender/receiver)
#filed contacts - the user's contact book, list of people they can contact
#field admins - and a list of admins, list of users who have admin
privileges over this Profile object
"""
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
usertype = models.CharField(max_length=30, default="sender")
contacts = ArrayField(models.CharField(max_length=150, default="default"), default=[])
admins = ArrayField(models.CharField(max_length=150, default="default"), default=[])
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
"""
#brief Describes a gram message that a sender type Profile is
able to send to a receiver type Profile.
#field send_username - the username of the sender profile
#field recp_username - the username of the receiver profile
#field sent_time - the time at which the Gram object was sent
#field display_until - the amount of time the Gram object will be visible
"""
class Gram(models.Model):
message = models.CharField(max_length=240)
send_username = models.CharField(max_length=150, default="default")
recp_username = models.CharField(max_length=150, default="default")
sent_time = models.DateTimeField(null=True)
display_until = models.DateTimeField(null=True)
def __str__(self):
return self.message
#function checks if another user can be added to the list of contacts
#active_user_type - logged in user; new_contact - the contact to be added
def validated_contact_add(active_user_type,new_contact):
#check if the contact exists in the list of users
if User.objects.filter(username=new_contact).exists():
#check if the type of the logged in user is different from the one being added
if active_user_type != Profile.objects.get(user=User.objects.get(username = new_contact)).usertype:
return "valid"
else:
return "wrong type"
else:
return "does not exist"
_________THINGS I'VE TRIED TO RESOLVE THIS (but failed):_______________
deleting db
deleting local repository and recloning, and deleting db
makemigrations auth and makemigrations (there were no
migrations to make)
using --fake (as suggested in
Django 1.8 test issue: ProgrammingError: relation "auth_user" does not exist)
turning computer on an off again (as you can see, I'm pretty desperate)
Ok, so it turned out that some migrations were being skipped (?) when calling python manage.py makemigrations so I had to specify which app that I wanted to make migrations for. Calling python manage.py makemigrations grams (my target app name) fixed the problem.
I've defined a custom user model:
class User(AbstractUser):
REQUIRED_FIELDS = []
USERNAME_FIELD = 'email'
email = models.EmailField(
_('email address'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Must be a valid email address.'),
error_messages={
'unique':_("A user with that email address already exists."),
},
)
The point of it being to use an email address instead of username.
I've put this in settings:
# custom user model
AUTH_USER_MODEL = 'workoutcal.User'
The user model works, but there's one problem. I can't create superusers:
(workout) n155-p250:workout sahandzarrinkoub$ ./manage.py createsuperuser
Email address: sahandz#kth.se
Password:
Password (again):
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute
return super().execute(*args, **options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'
Seems like the create_superuser method used has username as a required argument. I've read in the docs that I need to implement my own CustomUserManager. I've already done so here:
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('email must be set')
email = self.normalize_email(email)
user = User(email = email, is_staff=is_staff,
is_superuser=is_superuser, date_joined=now,
**extra_fields)
user.set_password(password)
user.save()
return user
def create_user(self, email, password, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
It seems clear that my CustomUserManager isn't managing the User model. There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model. Could somebody tell me how to do that?
You also need to tell the new user to use the new manager:
class User(AbstractUser): # in your custom user
#...
objects = CustomUserManager()
#...
Django does the same thing in the source code at line 325
As for:
There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model.
Yes, there is actually a nice doc for that too, but explained in a more general way:
https://docs.djangoproject.com/en/2.0/topics/db/managers/
I have the need of create an user account in my application using just the email and password fields. Due to this, my custom user model in my models.py is:
I customize the UserManager to create user
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError("Users must have an email address")
email = self.normalize_email(email)
user = self.model(email = email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
And my User model is:
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import ugettext_lazy as _
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, null=True,
help_text=_('Required. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid email address.'), 'invalid')
])
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
objects = UserManager()
USERNAME_FIELD = "email"
class Meta:
db_table = 'auth_user'
verbose_name_plural = 'Usuarios en la plataforma'
def __str__(self):
return "#{}".format(self.email)
In my settings I've add:
AUTH_USER_MODEL = ‘my_app_name.User’
CREATE USERS - UserCreationForm pre-built class
To create an user, I am using of the UserCreationForm class pre-built in the django core.
In this class the username field is used such as denoted here
According to the above, in my forms.py I have:
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = get_user_model()
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("email", "password1", "password2",)
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["email"].label = "Email address"
When I try execute the python manage.py makemigrations , I get this traceback output error
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/bgarcial/.virtualenvs/ihost/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 "/home/bgarcial/.virtualenvs/ihost/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 "/home/bgarcial/workspace/ihost_project/accounts/admin.py", line 8, in <module>
from .forms import CustomUserChangeForm, CustomUserCreationForm
File "/home/bgarcial/workspace/ihost_project/accounts/forms.py", line 16, in <module>
class CustomUserCreationForm(UserCreationForm):
File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/forms/models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
(ihost)
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
Of course, I am using UserCreationForm django class core, I am forcing to use the django core functionalities in which the username field is required
How to can I remove the username or modify this?
I know the modify the django core is not recommended, but, how to can I create an user without include the username field making use of UserCreationForm django class core?
I try override the save method of my form in where I create the users, but I don't have clear the process, I think that the core of my inconvenient is in the use of UserCreationForm django class core ..
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("email", "password1", "password2",)
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["email"].label = "Email address"
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
# Tell to Django that not check the username
if commit:
user.save()
return user
If somebody can point me in the right direction will be very much appreciated. :)
I've found a solution that works.
anyways, feel free to suggest better solutions!
Like my inconvenient/error was related with the use of the UserCreationForm class pre-built in the django core which use the username field in their logic, then I proceeded to make the following:
In my forms.py in my class CustomUserCreationForm is a child of the class UserCreationForm, I've override/add to Meta class the attribute fields, using the email field instead of username field.
This question post help me with it.
My class CustomUserCreationForm stay as follow:
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = ('email',)
Then, I proceeded to perform my migrations:
[1] % python manage.py makemigrations accounts
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.User'.
This error showed me that the username field is not an attribute of my User model.
This means that Django follows trying to ask the username field, even though I overwritten the fields value with the email field.
Of course this is logic because I am still inherit from UserCreationForm class pre-built in the django core
Then, I've add the username field to my User model with null=True attribute, and of this way, the username does not required in the user account creation:
class User(AbstractBaseUser, PermissionsMixin):
# I had add the username field despite that I don't use in my User model
username = models.CharField(_('username'), max_length=30, null=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid username.'), 'invalid')
])
email = models.EmailField(unique=True, null=True,
help_text=_('Required. Letters, digits and ''#/./+/-/_ only.'),
validators=[RegexValidator(r'^[\w.#+-]+$', _('Enter a valid email address.'), 'invalid')
])
...
Of this way, I execute my migrations
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
[1] % python manage.py makemigrations accounts
Migrations for 'accounts':
accounts/migrations/0001_initial.py:
- Create model User
(ihost)
bgarcial#elpug ‹ testing ●● › : ~/workspace/ihost_project
python manage.py migrate accounts ...
And my username field still persist in my custom user schema, just that is not required and when I created an user from my UserCreateForm class which inherit from UserCreationForm, I can create an user account with just email and password
I don`t know if this is the best approach to address this inconvenient.
Feel free to suggest improvements!
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.