from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class News(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
headline = models.CharField(max_length=100)
content = models.CharField(max_length=1000000)
time_created = models.DateTimeField(default=datetime.now, blank=True)
i kept on trying this method but i keep getting an error" django.db.utils.OperationalError: no such column: blog_news.user_id "
I am trying to make a logged-in user view only his/her contributions
Did you use "python manage.py migrate" command? (and of course, after that "python manage.py makemigrations" command)
Probably, you didn't run these commands and the database can't find such a column.
Related
I have below code in Models.py
from django.db import models
class Post(models.Model):
text = models.TextField()
I have entered 100 around records to application which run using SQLite DB and Modified it in to following and migrate
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey("auth.User",on_delete=models.CASCADE,)
text= models.TextField()
When I try to migrate the changes using python manage.py makemigrations I am getting message regarding the 100 records that have null for author. What I need is to modify
above code to set any text without author must be setup as superuser by default.
I made the mistake of not using a custom user model for the first migration and I paid the price by having to delete all the migrations and makemigrations and migrate again as I switched the project to use my custom user.
models.py
"""
Changes are never picked by makemigrations
"""
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
username = models.CharField(max_length=120, unique=True, blank=False,
validators=[MinLengthValidator(2)])
email = models.EmailField('Email Address', unique=True, blank=False)
FCM_ID = models.CharField(max_length=300, blank=True)
def __str__(self):
return self.username
Everytime I made any changes to the custom user, I have had to delete all migrations related files and apply migrations again just to get past the errors- this SO answer and this.
Now I realized that I needed a newer change, but migrations are not detected after changing the User model. The only solution I have is to delete the migrations again! So far I have done this chore like 5 times and I am tired, what am I doing wrong?
I have tried python3 manage.py makemigration <app_name>, and of course, the custom user model is defined in settings.py using AUTH_USER_MODEL.
I'm pretty new to django and I'm stuck at the problem with models. Here is my users app's models file:
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
from django.urls import reverse
from PIL import Image
class Schedule(models.Model):
title = models.CharField(max_length=150)
context = models.TextField()
class Input(models.Model):
DAYS_OF_FITNESS = [
('month', '30'),
('month_2', '60'),
('month_3', '90'),
]
weight = models.PositiveIntegerField(validators=[MinValueValidator(40)])
age = models.PositiveIntegerField(validators=[MinValueValidator(12)])
days = models.CharField(
max_length=20, choices=DAYS_OF_FITNESS, default='30')
athlete = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
I'm trying to link each user with its input using OneToOneField and Schedule is linked as a foreign key to Input model
But when I'm trying to migrate models, I'm getting this error:
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: users_input
I checked that Both models are in django settings, and I migrated them. BTW, I'm using signals to save inputs automatically, (just for note if it helps)
It's because that table doesn't exist in the database. To create tables you have to do the following. Execute the following commands in your terminal.
python manage.py makemigrations
python manage.py migrate
I am following the tutorials
https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html
on making a simple user registration website.
The key model defined in model.py is
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
which creates the table profile in the database. My question is how do we append this table to include information like user's first/last name and email. I know those information is stored in auth_user, but it would nice to have everything on one table.
I am new to django platform. Any explanation or reference is greatly appreciated.
If you want to append first_name, last name, and email in Profile model then there is no need of this user = models.OneToOneField(User, on_delete=models.CASCADE)
so basically you can remove this line
and
append these field to the model like:
first_name = models.TextField(max_length=50, blank=True)
last_name = models.TextField(max_length=50, blank=True)
email = models.TextField(max_length=200, blank=True)
and run command: python manage.py makemigrations and then
python manage.py migrate
But i will not recomend you to do this.
I suggest you to use django auth user model because then you extra fetures of django very easily like maintaining sessions etc.
follow :- https://docs.djangoproject.com/en/2.0/intro/tutorial01/
I have a simple django app, and am trying to set up a custom Django User Model so that I can have users log in with their email field. I think I set everything up well enough, its all fairly straightforward, however when trying to actually run the migrations I get this error:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial
Seems weird?
I'm having trouble understanding why it's having trouble understanding.
Heres the User model Im implementing
from __future__ import unicode_literals
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
display_name = models.CharField(_('display name'), max_length=30, blank=True)
bio = models.TextField(blank=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
is_active = models.BooleanField(_('active'), default=True)
avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
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
def email_user(self, subject, message, from_email=None, **kwargs):
'''
Sends an email to this User.
'''
send_mail(subject, message, from_email, [self.email], **kwargs)
"Using a custom user model when starting a project"
If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises." reference->django docs
Then you have to specify to setting.py that you are using a new user model (again before you migrate for the first time.)
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
# in settings.py
AUTH_USER_MODEL = 'myapp.MyUser'
I highly recommend checking out the link above.
Now to solve your problem you can delete your migrations in your app path under the migrations directory and reset your database and follow the instructions above.
Changing user model mid project is difficult in django and requires manually editing your schema so since your project is for educational purposes just reset it
Basically, you have already created some User accounts or at least have created superuser account. Since you are changing the User model after I assume you have already made migrations at least once, Django has conflict with old user model with the new one.
Solution is to delete all accounts in admin including superuser. Then delete your migrations files in migrations folder. And also I think delete your sqlite data file. Run migrations again and it should work.
You should have created custom user model before any migration.
One solution is to truncate the django_migrations table.
To do this you have to:
login to your database (In case you use Mysql) using mysql -u root -p
use your_db_name;
SET FOREIGN_KEY_CHECKS=0; to prevent relation errors
DELETE FROM django_migrations; truncates the django_migrations table
SET FOREIGN_KEY_CHECKS=1;
Then you can run your migrations!
Another solution is to run these commands before your migration to avoid migrations error:
python manage.py migrate admin zero --fake
python manage.py migrate auth zero --fake
python manage.py migrate contenttypes zero --fake
python manage.py migrate sessions zero --fake
Warning :
This solution may leave you with a database schema that's
inconsistent with the migrations applied, so only do this if
you know what you're doing. Thanks to #AKX
You can also use this solution too!