How to can I create my own user model in Django, in which I want that my P.K be the username field and not the id field autogenerated by Django?
I am trying the following:
I've create the userprofiles application in where I will create my customize django user model
INSTALLED_APPS = [
...
'userprofiles.apps.UserprofilesConfig',
...
]
AUTH_USER_MODEL = 'userprofiles.User'
In my userprofiles/models.py file I have defined the following:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin
# Create your models here.
class User(AbstractBaseUser, PermissionsMixin):
GENDER_MALE = 'M'
GENDER_FEMALE = 'F'
GENDER_OTHER = 'O'
GENDER_CHOICES = (
(GENDER_MALE, u'Male'),
(GENDER_FEMALE, u'Female'),
)
username = models.CharField(max_length=15, unique=True, db_index=True, primary_key=True)
first_name=models.CharField(max_length=50, blank=False,)
last_name=models.CharField(max_length=50, blank=False,)
photo = models.ImageField(upload_to='avatars', blank=True)
email = models.EmailField(max_length=254, unique=True)
is_staff = models.BooleanField(
default=True,
help_text='Designates whether the user can log into this admin site.')
is_active = models.BooleanField(default=True)
#date_joined = models.DateTimeField(default=None)
#date_joined = models.DateTimeField()
gender = models.CharField(
max_length=1,
choices=GENDER_CHOICES,
blank=False, )
is_player = models.BooleanField(default=False)
is_coach = models.BooleanField(default=False)
is_viewer = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email',]
objects = UserManager()
class Meta:
db_table = 'auth_user'
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
I am using the AbstractBaseUser class due to:
AbstractBaseUser provides the core implementation of a User model,
including hashed passwords and tokenized password resets. You must
then provide some key implementation details: ...
and also I considered this explanation in which say that is necessary add manually the fields that I needed.
Then, when I perform the migrations the fields that I've defined in my User model (that inherit from AbstractBaseUser) are created in my database:
(fuupbol) ➜ fuupbol_project git:(master) ✗ python manage.py makemigrations
Migrations for 'userprofiles':
0013_auto_20160418_2252.py:
- Add field groups to user
- Add field user_permissions to user
- Alter field is_superuser on user
(fuupbol) ➜ fuupbol_project git:(master) ✗ python manage.py migrate
Operations to perform:
Apply all migrations: sessions, userprofiles, admin, contenttypes, auth
Running migrations:
Rendering model states... DONE
Applying userprofiles.0013_auto_20160418_2252... OK
(fuupbol) ➜ fuupbol_project git:(master) ✗
Then I've created a superuser via command line interface of this way:
(fuupbol) ➜ fuupbol_project git:(master) ✗ python manage.py createsuperuser
Username: cdiaz
Email: cdiaz#fuupbol.org
Password:
Password (again):
Superuser created successfully.
(fuupbol) ➜ fuupbol_project git:(master) ✗
In addition, I add these fields of my custom User model for that Django Admin can view them, of this way:
Like Django use special forms to create and edit forms in the admin relative to Users model, due to these was thinked only for the django original user model.
Here we are using a custom django user model with AbstractBaseUser, then we use the following class:
UserChangeForm which is applied to the User model, so this way is applied to the admin user form, and the UserCreationForm for that an user be created with from my user form customized with the previous modifications
In my userprofiles/forms.py file
from django import forms
from django.contrib.auth.forms import (UserChangeForm,UserCreationForm)
from .models import User
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
In my userprofiles/admin.py file create an CustomUserAdmin class customized with the fields defined before in my custom User model
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
from .forms import CustomUserChangeForm, CustomUserCreationForm
# Register your models here.
class CustomUserAdmin(UserAdmin):
form = CustomUserChangeForm
add_form = CustomUserCreationForm
fieldsets = UserAdmin.fieldsets + (
(
None, {
'fields':(
'username',
'password',
'first_name',
'last_name',
'gender',
'email',
'photo',
'is_staff',
'is_active',
'is_superuser',
'is_player',
'is_coach',
'is_viewer',
'last_login',
)
}
),
)
#Change our UserAdmin class to inherit of our CustomUserAdmin created above (do not inherit of model.ModelAdmin)
#admin.register(User)
class UserAdmin(CustomUserAdmin):
list_display = ('username','password','first_name','last_name','gender','email','photo','is_staff','is_active','is_superuser','is_player','is_coach','is_viewer','last_login',)
Then when I go to the Django admin and I see the options to edit some user already created, I get this message:
In this moment I do not have the date_joined attribute in my User model, and if I add the date_joined attribute to my User model, and perform the migrations, I get this messages:
(fuupbol) ➜ fuupbol_project git:(master) ✗ python manage.py makemigrations userprofiles
Migrations for 'userprofiles':
0022_user_date_joined.py:
- Add field date_joined to user
(fuupbol) ➜ fuupbol_project git:(master) ✗
And when I execute the migrate command
(fuupbol) ➜ fuupbol_project git:(master) ✗ python manage.py migrate userprofiles
Operations to perform:
Apply all migrations: userprofiles
Running migrations:
Rendering model states... DONE
Applying userprofiles.0015_user_date_joined...Traceback (most recent call last):
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: column "date_joined" contains null values
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 396, in add_field
self.execute(sql, params)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/bgarcial/.virtualenvs/fuupbol/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: column "date_joined" contains null values
(fuupbol) ➜ fuupbol_project git:(master) ✗
I cannot understand the reason of the error message django.db.utils.IntegrityError: column "date_joined" contains null values due to in this moment I do not have this attribute date_joined
Any orientation would be appreciated.
Thanks
I am assuming you don't have data for date_joined on any of the instances and one of the migrations requires it to not be be null. You can probably either go into the database and add it manual to get around it temporarily.
Related
I had a model Profile which was an extension to my User model which was the ForeignKey of my Post model, but I changed it to an AbstractUser and now if I try migrating or running and refreshing the page the server I get an error.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio = models.TextField(max_length=500,null=True)
from django.db import models
from django.conf import settings
from django.urls import reverse
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=100)
content = models.TextField()
def get_absolute_url(self):
return reverse('post-details', kwargs={'pk': self.pk})
settings.py
INSTALLED_APPS = [
...
'posts',
'users',
]
AUTH_USER_MODEL = 'users.User'
error message after I try migrating
Apply all migrations: admin, auth, contenttypes, posts, sessions, users
Traceback (most recent call last):
File "/home/user/Projects/DNF/Project/manage.py", line 22, in <module>
main()
File "/home/user/Projects/DNF/Project/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/commands/migrate.py", line 295, in handle
pre_migrate_apps = pre_migrate_state.apps
File "/usr/local/lib/python3.10/dist-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 566, in apps
return StateApps(self.real_apps, self.models)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 637, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field posts.Post.author was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field users.Profile.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
I easily solved it by deleting all the migration files in the migrations folder except the init.py file. And also delete db.sqlite3. Now run the following commands : python manage.py makemigrations and then python manage.py migrate. Now you'll have to create the super user once again, so for this just type the following commmand : python manage.py createsuperuser. Then it will prompt for username, email and password, so enter your credentials and all will continue to work properly once again I hope that this will be helpful.
try to directly reference the User model, not through settings
change the foreign key field to this:
author = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True)
To have a reference to the User model, you should not do through settings directly instead you can use get_user_model() function. This function will return the currently active User model of project( the custom User model if one is specified, or User otherwise).
So change the foreign key field of your Post model like below:
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
...
Reference: get_user_model() [Django-doc]
I created a model like this.
class BloodDiscard(models.Model):
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True)
blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True)
blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True)
quantity = models.FloatField()
But now I need to apply inheritance to my model, like this. [(models.Model) ---> (BaseModel)]
class BloodDiscard(BaseModel):
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True)
blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True)
blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True)
quantity = models.FloatField()
BaseModel is another model I created before but forgot to inherit it in my current model.
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status_master = models.ForeignKey(StatusMaster,on_delete=models.SET_NULL,default=3,null=True, blank=True)
I applied "python manage.py makemigrations" after changing (models.Model) ---> (BaseModel) and got this...
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py makemigrations
You are trying to add the field 'created_at' with 'auto_now_add=True' to blooddiscard without a default; the database needs something to populate existing rows.
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>>
Migrations for 'Form':
Form\migrations\0018_auto_20220622_2322.py
- Add field created_at to blooddiscard
- Add field status_master to blooddiscard
- Add field updated_at to blooddiscard
But after that when I am applying "python manage.py migrate". I am getting this error.
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py migrate
Operations to perform:
Apply all migrations: Form, Master, User, admin, auth, contenttypes, sessions
Running migrations:
Applying Form.0018_auto_20220622_2322...Traceback (most recent call last):
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.ForeignKeyViolation: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "G:\office\medicover\medicover_bloodbank_django\venv\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 "G:\office\medicover\medicover_bloodbank_django\venv\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 "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
schema_editor.add_field(
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\base\schema.py", line 522, in add_field
self.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute
cursor.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
And when doing "python manage.py runserver" getting this...
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): Form.
Run 'python manage.py migrate' to apply them.
June 22, 2022 - 23:23:51
Django version 3.2.5, using settings 'App.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
NOTE:-
In StatusMaster table there's only two rows having id's 1 and 2.
That will not work, since BaseModel is a non-abstract model, and thus the BaseModel and the BloodDiscard share the same "primary key space": the primary key of the BloodDiscard is a ForeignKey to the BaseModel primary key.
Likely you do not want BaseModel to be a non-abstract model, but an abstract one, so you can rewrite BaseModel to:
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status_master = models.ForeignKey(
StatusMaster,
on_delete=models.SET_NULL,
default=3,
null=True,
blank=True
)
class Meta:
abstract = True
Remove the problematic migration file, make a new migration file, and migrate.
This is the error I was getting:-
django.db.utils.IntegrityError: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
as we can see:-
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
it is telling me that in status_master, there is no "id" (PK) having the value "3".
however, in my base model:-
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status_master =
models.ForeignKey(StatusMaster,on_delete=models.SET_NULL,default=3,null=True, blank=True)
someone provided a default value "3" of "status_master" which does not exist. So, I simply just removed the default value and it got solved.
models.py
from __future__ import unicode_literals
from django.db.models.signals import post_save
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
class Friend(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name = 'owner',null=True)
#classmethod
def make_friend(cls, current_user, new_friend):
friend, created = cls.objects.get_or_create(
current_user = current_user
)
friend.users.add(new_friend)
#classmethod
def lose_friend(cls, current_user, new_friend):
friend, created = cls.objects.get_or_create(
current_user = current_user
)
friend.users.remove(new_friend)
class Post(models.Model):
post=models.CharField(max_length=500)
user=models.ForeignKey(User)
data = models.DateTimeField(auto_now=True)
class UserProfileManager(models.Manager):
def queryset(self):
return super(UserProfileManager,self).get(queryset).filter(city='surat')
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100,default='')
city = models.CharField(max_length=100,default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
image = models.ImageField(upload_to='profile_image',blank=True)
surat = UserProfileManager()
def __str__(self):
return self.user.username
def create_profile(sender,**kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile,sender=User)
views.py
from django.http import HttpResponse
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from tutorial import views
from accounts.forms import Registrationform,EditProfileForm
from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from .forms import HomeForm
from .models import Post,Friend
class HomeView(TemplateView):
template_name = 'accounts/home.html'
def get(self,request):
form = HomeForm()
posts=Post.objects.all()
users = User.objects.exclude(id=request.user.id)
friend =Friend.objects.get(current_user=request.user)
friends = friend.users.all()
args={
'form':form,'posts':posts,'users':users,'friends': friends
}
return render(request,self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
if form.is_valid():
post=form.save(commit=False)
post.user=request.user
post.save()
text =form.cleaned_data['post']
form = HomeForm()
return redirect('accounts:home')
args = {'form' : form,'text' : text}
return render(request, self.template_name,args)
def change_friends(request, operation, pk):
new_friend = User.objects.get(pk=pk)
if operation == 'add':
Friend.make_friend(request.user, new_friend)
elif operation == 'remove':
Friend.lose_friend(request.user, new_friend)
return redirect ('accounts:home')
def register(request):
if request.method == "POST":
form = Registrationform(request.POST)
if form.is_valid():
form.save()
return redirect('/accounts')
else:
return HttpResponse('please fill all the fields and make sure new password must be match')
else:
form = Registrationform()
args={'form' : form}
return render(request,'accounts/reg_form.html',args)
#login_required
def view_profile(request,pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user' : user}
return render(request,'accounts/profile.html',args)
#login_required
def edit_profile(request):
if request.user.is_authenticated():
#<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
if request.method=="POST":
form = EditProfileForm(request.POST,instance=request.user)
if form.is_valid():
form.save()
return redirect('/accounts/profile')
else:
return HttpResponse("please go back and write correct values")
else:
form = EditProfileForm(instance=request.user)
args = {'form' : form}
return render(request,'accounts/edit_profile.html',args)
else:
HttpResponse("hllo")
return redirect('/accounts/login')
#login_required
def change_password(request):
if request.user.is_authenticated():
if request.method == "POST":
form = PasswordChangeForm(data=request.POST,user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect('/accounts/profile')
else:
return HttpResponse("password does not match,go back and try again")
else:
form = PasswordChangeForm(user=request.user)
args = {'form' : form}
return render(request,'accounts/change_password.html',args)
else:
return redirect ('/accounts/login')
form.py
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django.contrib.auth.models import User
#from django.forms import RegistrationForm,EditProfileForm
from django import forms
from accounts.models import Post
class HomeForm(forms.ModelForm):
post = forms.CharField(widget=forms.TextInput(
attrs={
'class':'form-control',
'placeholder' : 'write a post'
}
))
class Meta:
model = Post
fields = ('post',)
class Registrationform(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
)
def save(self,commit=True):
user=super(Registrationform,self).save(commit=False)
user.first_name= self.cleaned_data['first_name']
user.last_name=self.cleaned_data['last_name']
user.email=self.cleaned_data['email']
if commit:
user.save()
return user
class EditProfileForm(UserChangeForm):
#template_name = '/something/else'
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
'password'
)
and the error is
(.vEnv) jayu#broadwell-gt2:~/Desktop/tutorial$ heroku run python manage.py migrate
› Warning: heroku update available from 7.0.82 to 7.0.83
Running python manage.py migrate on ⬢ jaysuthar... up, run.5398 (Free)
/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
Operations to perform:
Apply all migrations: accounts, contenttypes, auth, admin, sessions
Running migrations:
Rendering model states... DONE
Applying accounts.0002_auto_20180514_0523...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 482, in alter_field
old_db_params, new_db_params, strict)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 564, in _alter_field
old_default = self.effective_default(old_field)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 210, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save
prepared=False)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 720, in get_db_prep_value
value = self.get_prep_value(value)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1853, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: ''
Django keeps throwing the following when I deploying project (error is in migrate time when i run heroku run python manage.py migrate)
ValueError: invalid literal for int() with base 10: ''
i want to deploy this project on heroku, it successfully run till
git push heroku master --forc
but when i migrate database with this command :
heroku run python manage.py migrate
it gives error of valueerror.
where i did mistake ?
If you can provide any help I would greatly appreciate it.
EDIT :
accounts.0002_auto_20180514_0523 file :
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2018-05-14 05:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='phone',
field=models.IntegerField(default=0),
),
]
Obviously in it's first version your UserProfile's "phone" field was a CharField defaulting to the empty string. Changing an existing field's type requires a three-steps migrations: first create a new field with the desired type, create and apply the migration, then create a datamigration that will copy original data to the new field with proper transformations, error handling etc, and finally delete the original field (create and apply the migration).
BUT : in your case, making this field an integer is just plain wrong. A phone number is NOT an integer. First because you cannot add, substract, multiply or divide phone numbers, then because a phone number can contain non-numeric characters too (cf international phone numbers formats).
Thinking that everything made of numeric characters should be an int is a common beginner mistake (just like using floats instead of decimals for prices storage and calculations). When in doubt, ask yourself whether applying mathematical operations would make sense...
I'm creating a blog using Django and anytime I run manage.py migrate, I get the error below:
(venv) (C:\Users\KOLAPO\Anaconda3) C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads>manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, taggit
Running migrations:
Applying blog.0001_initial...Traceback (most recent call last):
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 62, in execute
return self.cursor.execute(sql)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: table "blog_post" already exists
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads\manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
fake_initial=fake_initial,
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\operations\models.py", line 96, in database_forwards
schema_editor.create_model(model)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\base\schema.py", line 295, in create_model
self.execute(sql, params or None)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\base\schema.py", line 112, in execute
cursor.execute(sql, params)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 62, in execute
return self.cursor.execute(sql)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: table "blog_post" already exists
Here's everything in my models.py file:
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from taggit.managers import TaggableManager
from ckeditor_uploader.fields import RichTextUploadingField
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
subtitle = models.TextField()
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, related_name='blog_posts')
image = models.ImageField(upload_to='posts/%Y/%m/%d', blank=True)
# body = models.TextField()
body = RichTextUploadingField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
tags = TaggableManager()
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[
self.publish.year, self.publish.strftime('%m'),
self.publish.strftime('%d'), self.slug])
objects = models.Manager() # default manager
published = PublishedManager() # custom manager
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
image = models.ImageField(upload_to='users/%Y/%m/%d', null=True, blank=True)
#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()
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
class Feedback(models.Model):
name = models.CharField(max_length=200, help_text="name of sender")
email = models.EmailField(max_length=200)
subject = models.CharField(max_length=200)
message = models.TextField()
date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = "Feedback"
def __str__(self):
return (self.name, "-", self.email)
I'm stuck on that error. How do I fix it please?
Maybe faking the initial migration of blog app will help you. Try the following.
./manage.py migrate --fake blog 0001_initial
Django 3.2
The following worked for me:
delete all the migration files, including the initial migration. Then perform:
python manage.py makemigrations
python manage.py migrate
Every time I see this kind of question I wondered: if the model.py is ok, why does no one suggests (in the answer) dropping the wrong table and - instead - almost everybody suggests deleting all migration files? It's overkill!
If model.py is proper and ok now, then you can always do two things:
Edit migration files - instead of deleting them. If this doesn't work, then:
With SQL shell: drop a single (wrong) table by accessing it via SQLite or PostgreSQL - depending on the one that you are using. Also, you can edit and update it.
Update:
There are some cases when things get more tricky. If the problem is related to the foreign key that was added to the particular table in SQLite, then it's more difficult to solve the problem, than having the same issue but with PostgreSQL. The SQLite is lacking some very handy features like removing a column that has foreign keys. I had a few situations where the first error was related to some table that I needed to drop, but after that, another issue was with a foreign key. Because both problems were related to some model that had a one-to-many relation. That's why I recommend getting familiar with PostgreSQL. That will make it easier to solve this kind of situation without deleting a whole database.
Getting this error when running python manage.py migrate:
ValueError: Lookup failed for model referenced by field account.UserProfile.user: auth.User
Steps I did:
1. Created project and added new app:
$ django-admin.py startproject djdev
$ cd djdev
$ python manage.py startapp account
2. I added new app to INSTALLED_APPS in djdev/settings.py:
...
'django.contrib.staticfiles',
'account',
)
...
3. Created a new UserProfile model class in account/models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
"""
User Profile having one-to-one relations with User
"""
class Meta:
db_table = 'user_profile'
ordering = ['id']
user = models.OneToOneField(User, db_column='id_user', related_name='profile')
mobile_no = models.CharField('Mobile no.', db_column='contact_no_home', max_length=16, blank=True, null=True)
address_line_1 = models.CharField('Address Line 1', db_column='contact_address_line_1_home', max_length=140, blank=True, null=True)
address_line_2 = models.CharField('Address Line 2', db_column='contact_address_line_2_home', max_length=140, blank=True, null=True)
office_mobile_no = models.CharField('Mobile no.', db_column='contact_no_office', max_length=16, blank=True, null=True)
office_address_line_1 = models.CharField('Address Line 1', db_column='contact_address_line_1_office', max_length=140, blank=True, null=True)
office_address_line_2 = models.CharField('Address Line 2', db_column='contact_address_line_2_office', max_length=140, blank=True, null=True)
about = models.TextField('About me', blank=True, null=True)
note = models.CharField('Note', max_length=255, blank=True, null=True)
def __unicode__(self):
return self.user.name
4. Started migrating:
$ python manage.py makemigrations account
$ python manage.py migrate
After executing last command python manage.py migrate I'm getting this error:
Operations to perform:
Synchronize unmigrated apps: (none)
Apply all migrations: admin, contenttypes, account, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
Applying account.0001_initial...Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/vinay/python_webapps/django-trunk/django/core/management/__init__.py", line 427, in execute_from_command_line
utility.execute()
File "/home/vinay/python_webapps/django-trunk/django/core/management/__init__.py", line 419, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/vinay/python_webapps/django-trunk/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/vinay/python_webapps/django-trunk/django/core/management/base.py", line 337, in execute
output = self.handle(*args, **options)
File "/home/vinay/python_webapps/django-trunk/django/core/management/commands/migrate.py", line 146, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 62, in migrate
self.apply_migration(migration, fake=fake)
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 90, in apply_migration
if self.detect_soft_applied(migration):
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/executor.py", line 134, in detect_soft_applied
apps = project_state.render()
File "/home/vinay/python_webapps/django-trunk/django/db/migrations/state.py", line 83, in render
model=lookup_model
ValueError: Lookup failed for model referenced by field account.UserProfile.user: auth.User
NOTE: Django Version I'm using: 1.8.dev20140507130401
This is already fixed in the master branch.
Fixed in commits:
https://code.djangoproject.com/changeset/8f6dff372b174e772920de6d82bd085f1a74eaf2
https://code.djangoproject.com/changeset/35c2a14a49ac3cb25dcff818b280bf0b4c290287
You can install it until a proper release is built:
pip install https://github.com/django/django/zipball/master
Test:
models.py
from django.db import models
from django.contrib.auth.models import User
class Test(models.Model):
user = models.OneToOneField(User)
Results
[__env] $ ./manage.py makemigrations
Migrations for 'data':
0001_initial.py:
- Create model Test
[__env] $ ./manage.py migrate
Operations to perform:
Synchronize unmigrated apps: admin, contenttypes, auth, sessions
(... ommited ...)
Running migrations:
Applying data.0001_initial... OK
I read the comment above as suggesting adding only the last line in the dependencies list (('contenttypes',' __first__')), but I had to add the last two to correct the problem. This might be obvious to those with a better understanding of the makemigrations tool in Django, but I am new to it and it was not to me.
My last migrations file dependencies list that was originally giving the same error...
dependencies = [
('myapp', '0006_auto_20150209_0324'),
(b'auth', b'__first__'),
(b'contenttypes', b'__first__'),
]
I've found another solution that also work fine.
See the solution of by rockallite.wulf#
https://code.djangoproject.com/ticket/22488
Just add the corresponding dependency in the migration file, like this:
dependencies = [
(b'advperm', b'0001_initial'),
(b'auth', b'__first__'),
(b'contenttypes', b'__first__'), # Add this line
]