How to add new columns to django userprofile model - python

I have added one extra custom field phone to Django user authentication. Till then it worked properly. Later I added one more custom field called permissions. After that I am facing an error message when I try to access the admin page. Here is my model.py code
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
class Meta:
permissions = (
("ssc_1","can access ssc locked questions"),
)
# The additional attributes we wish to include.
phone = models.CharField(max_length =20)
permission = models.IntegerField()
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
I have followed this stackoverflow answer, when I issue python manage.py migrate command, I am getting this error message
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: table "users_userprofile" already exists
Note : My Django versions is 1.6.6
Thanks

Migrations were introduced only in django 1.7. Until then south was being used to handle migrations

Related

How to add one custom column in Django built in auth_user table

I'm trying to add one status field in my django auth_user(Built In) table. I'm using the below code.
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import User
class Auth_user(AbstractBaseUser):
status = models.CharField(max_length=12,unique=True)
USERNAME_FIELD = 'status'
An in the settings.py I'm mentioning like this.
AUTH_USER_MODEL = "accounts.Auth_user"
but the status field is not getting added in the table auth_user.Can somebody suggest how to add custom (column)field in Django in built table?
change the name of your class
instead of class Auth_user() you should use class User()
and also dont forget to migrate.
for more information go through this code given below
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
You have to create migration (python manage.py makemigrations) and then migrate the db (python manage.py migrate) for changes in models to be reflected in the database.
Extend the model as following -->
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
status = models.CharField(max_length=12,unique=True)
USERNAME_FIELD = 'status'
then create the make migrations file and migrate db

Limit custom migration to one model

I have decided to implement registration option for my website, I used this tutorial (signup with confirmation part). Following this material I have created Profile module to hold some info. Everything (seems to be) working now, but the problem is that old profiles throws relatedObjectDoesNotExist error. According to these two questions (first, second) I need to make a migration to create profiles for old user accounts. I tried to follow this doc as suggested in one of the answers, but then I try to run a migration I get following error: KeyError: ('stv', 'bazinekaina')
stv is the name of my app and bazinekaina is the name of the next model after the one I need to create profiles.
How to limit migration to only the first model?
My relevant models.py code:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email_confirmed = models.BooleanField(default=False)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length=254)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.get(user=instance)
instance.profile.save()
#next model, this one throws an error, despite the fact it should not be touched at all
class BazineKaina(models.Model):
#bazines kainos modelis
bazka = models.DecimalField(max_digits=5, decimal_places=2)
data = models.DateField(auto_now=False, auto_now_add=True)
def __str__(self):
return str(self.bazka)
class Meta:
verbose_name_plural = "BazinÄ— kaina"
get_latest_by = 'data'
Migration file crated after using python manage.py makemigrations --empty stv command, named 0001_initial.py:
from django.db import migrations, models
def sukurti_profilius(apps, schema_editor):
Profile = apps.get_model("stv", "Profile")
for user in Profile.objects.all():
Profile.objects.get_or_create(user=user)
class Migration(migrations.Migration):
dependencies = [
]
operations = [
]
How and what I should fix to stop migrations from applying to the unrelated models (and throwing error)?
Sorry if it is basic question, but whole django is still very new to me.
If your migration is named 0001_initial then it means that you don't have a migration that actually creates the table for the profile model.
Remove that migration and run:
python manage.py makemigrations stv
python manage.py makemigrations stv --empty --name create_profiles
Then you should have a file 0002_create_profiles.py and put the logic to create profiles there.

Django User model foreign key failed

I am using django 2.0. For users I am using the model django.contrib.auth.models.User. I have stored a user with username john in it. I have a Post model which uses a User model as ForeignKey. This is my models.py:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
post_content = models.CharField(max_length=140)
post_date = models.DateTimeField('post date')
post_user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.post_content
...In my views.py I am creating a post with:
from django.contrib.models import User
Post.objects.create(post_content=post_text, post_date=timezone.now(),post_user=User.objects.get(username='john'))
...In one part of the code. When I run I get this error:
FOREIGN KEY constraint failed
IntegrityError at /
And it points to the line in which I create the user in views.py.
Is there a proper way to ForeignKey a user model? Any guidance appreciated. Thank you :-).
EDIT:It works after doing a reset to the database because I made an error with migrations. Run you migrations properly friends!

User with permission to modify only one field of the model in the Django Admin

I have a user named ExpertUser who should only be able to modify an attribute of the called model (money) of the users in the Django Admin.
I have tried adding permissions in the model using the Meta but when entering with that permission I can not modify anything since I do not have access to any user.
My model is this:
class Client(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
money = models.FloatField(default=1000)
def __str__(self):
return self.user.username
class Meta:
permissions = (("can_view_money", "Can view money"),)
Have a look at Django Guardian. That provides more flexibility in assigning permissions on various levels. Django only lets you set permissions at object level, so in your case you were only able to set permission to create/edit/delete Client objects.
http://django-guardian.readthedocs.io/en/v1.4.8/index.html
If that doesn't suffice, there are a few other packages with the desired functionality:
https://djangopackages.org/grids/g/perms/

Django IntegrityError on user signup

I am getting an error when I try to extend user profile using django-allauth
Exception Type: IntegrityError at /accounts/signup/
Exception Value: workerapp_userprofile.user_id may not be NULL
This is my models.py in my workerapp app of my django project where I am asking for two additional fields along with other signup information.
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User, unique=True)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
My user is saving correctly which I can see in the admin, it's just the showing this error during the signup.

Categories