After completed, I pushed and rebase git master, database in my project is locked. I removed database and create new, but I don't see table for Model in models.py. How should I fix? Help me
models.py
class UserInfor(models.Model):
GENDERS = (
('nam', "Nam"),
('nữ', "Nữ"),
('khác', "Khác")
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
date_of_birth = models.DateField(null=True)
gender = models.CharField(choices=GENDERS, max_length=10)
address = models.CharField(max_length=255, null=True)
phone_number = models.CharField(max_length=10, null=True)
def __str__(self):
return self.user.username
error
No changes detected
You should run python manage.py migrate to re-create your DB from scratch as you deleted it.
Run below command:
python manage.py makemigrations
Then:
python manage.py migrate
First make sure your app has been added to your project's settings.py
example:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
...................
...................
'yourappname'
]
If you've done that already, check and see if you've also registered your UserInfor model in your 'admin.py`
from .models import UserInfor
admin.site.register(UserInfor)
If all the above checks out, you should be able to run your migrations and see your model's table.
Try to delete db and files from migrations folder except init.py
then python manage.py makemigrations and python manage.py migrate
Related
I am new to Django, and im trying to create a company profile for user to fill up.
when i make migrations, i got the following error which is no changes detect.
heres the model.py
class Company(models.Model):
name = models.CharField(max_length=100)
about = models.TextField(gettext_lazy('about'), max_length=500, blank=True)
role = models.CharField(max_length=100)
address=models.CharField(max_length=100)
contact=models.CharField(max_length=100)
def __str__(self):
return f'{self.user.username} Profile'
I didnt create anything in other .py file only model and i have another class which is profile in the same model.py as company.
Do correct or lmk if i make any mistake, thanks!
Your app must be included in INSTALLED_APPS first (inside settings.py).
INSTALLED_APPS = [
...
'<myapp>',
...
]
After that you can run
python manage.py makemigrations <myapp>
After experimenting with setting up CustomUser and many-to-many relationships, I decided to make some (what turned out to be major) changes to the models. I had read that CustomUser/Auth needs to be set up first, or else it'll be a mess. But since I'm just learning and there was barely any data involved, I just went for it--not to mess up the CustomUser model intentionally, but I changed a model name--and (maybe this is the critical error) I updated the names everywhere it appeared. Now I'd deleted and reset the database, VENV folder, all the migration (along with __pycache__) files, and recreated test data so many times that I thought I could download the GitHub repo and set up a fresh new app easily again. But the app refuses to run and keeps asking for a missing table.
Re-creating the app isn't my main concern-I'd like to understand what happened-what is this missing table (see the snippet of the error code)? AND: Why is a perfectly intact repo having the same issue with the missing table?
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Volumes/Volume2/dev/lms6-v2/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Volumes/Volume2/dev/lms6-v2/venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 477, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: accounts_staff
The app is called accounts and the CustomUser models are:
class CustomUser(AbstractUser):
user_type_data = ((1, "HOD"), (2, "Staff"), (3, "Student"))
user_type = models.PositiveSmallIntegerField(default=1, choices=user_type_data)
email = models.EmailField(_('email address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
class AdminHOD(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
class Staff(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
user_type = "Staff"
email = models.EmailField()
address = models.TextField(blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
note = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.admin.first_name + " " + self.admin.last_name
def get_absolute_url(self):
return reverse('staff_detail', kwargs={'pk': self.pk})
first of all u need to delete all your migrations files(sure u have ) and the (pycache) ...
After you have done that dont just run makemigration u have to be logical with it
run python manage.py makemigrations <app_name:the app that contains the AUTH_USER_MODEL>
run python manage.py makemigrations <app_name> but this time u decide what app comes next in the way u wrote ur models they makemigrations in that order'
3)run python manage.py makemigrations
4)lastly run python manage.py migrations
... this how i solved this issue anytime i run into this problems
Obviously messing with the CustomUser model in Django isn't to be attempted casually, but this was a good learning experience. So for the newly initiated accidentally stuck at the same spot, the answer by Ogechuwku Matthew is a good start.
To elaborate-this is what I did:
Deleted all the migration files, including files in __pycache__ (EXCEPT for the __init__ file(s).
Disabled the AUTH_USER_MODEL = 'myapp.MyCustomUser' line in settings.py This step is key.
Removed (or commented out) all but the most essential files.
Commented out all but the CustomUser model and models extended from it.
Ran python manage.py makemigrations <app_name> and then 'python manage.py migrate`
After step 4 worked, ran python manage.py makemigrations <app_name> and python manage.py migrate again.
Moved the rest of the files back in, starting with the simplest bits, like 'HomeView' in views.py and 'home.html'.
When the app started up with 'home.html', un-commented models, views, and urls one cluster at a time.
Additionally: If error occur when running the app, first check the embedded dynamic links--they may extend or include files that aren't there yet-same with {% load static %}
I created a amount field in models.py,
I run python manage.py makemigrations and python manage.py migrate
It gave me error ValueError: Field 'amount' expected a number but got ''.
then I removed this amount field line from my code and again did makemigrations and migrate command. now again it it showing same error. when I open Django admin page and select my model name which is Orderss . It gives me error that there is no filed name amount
class Orders(models.Model):
order_id = models.AutoField(primary_key = True)
items_json = models.CharField(max_length=5000)
name = models.CharField(max_length=20)
# amount = models.IntegerField(default=0)
email = models.CharField(max_length=20)
address = models.CharField(max_length=50)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
zip_code = models.IntegerField(max_length=6)
phone = models.IntegerField(max_length=12, default="")
def __str__(self):
return self.name
Delete your migrations and delete you db.sqlite3
and then
python3 manage.py makemigrations
python3 manage.py migrate
hope it work
When you did the migration first time, you’ve created the table in the database with ‘amount’ column. The second migration did’t remove this column. You can go to your database shell and remove the column there. It depends on the type of database you use, but you you might try to do it this way:
python manage.py dbshell
mysql> | psql> ALTER TABLE <table_name> DROP column <COLUMN_NAME>;
Then exit the shell and sync
python manage.py syncdb
1.In the Migration folder delete all files except __init__.py and then run
python manage.py makemigrations and
python manage.py migrate
I am writing a apps and run makemigrations and migrate multiple time when i add new field.
And now i have added a new foreignKey Field in models and then i run the command:
python3 manage.py makemigrations
after this, i run this command python3 manage.py migrate but it throws me following error
TypeError: an integer is required (got type str)
and later again i run this command pythion3 manage.py migrate --fake and i have successfully migrated and got another problem, when i go to django admin templates and click on my models to add data, it throws me this error:
OperationalError at /admin/booking/seats/
no such column: booking_seats.seat_for_id
I am not getting whats wrong with it, can anyone help me to fix this?
for your reference, see my models:
class Seats(models.Model):
alias = models.UUIDField(
primary_key=True,
default=uuid4,
editable=False
)
seat_no = models.IntegerField(
choices=SeatChoices.choices(),
)
availability = models.IntegerField(
choices=SeatAvailability.choices(),
default=SeatAvailability.AVAILABLE
)
seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE)
def __str__(self):
return str(self.seat_no)
class Show(models.Model):
alias = models.UUIDField(
primary_key=True,
default=uuid4,
editable=False
)
show_schedule = models.IntegerField(
choices=ShowSchedule.choices(),
)
movie = models.CharField(max_length=50)
def __str__(self):
return str(self.show_schedule)
I just added this new field seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE) then i facing the problem
Can anyone help me in this case?
I think the problem is that your model is not with a capital, as Python is case sensitive. It should be like this:
seat_for = models.ForeignKey('booking.Show', on_delete=models.CASCADE)
I have an already existing app with alot of database entries.
class Foo(models.Model):
value = models.TextField(u"Value")
For this I do this:
python manage.py schemamigration myapp --initial
python manage.py migrate myapp
I change the model to such:
class Foo(models.Model):
value = models.TextField(u"Value")
live = models.BooleanField(u"Live", default=False)
creation_time = models.DateTimeField("Creation Time", auto_now_add=True, null=True, blank=True)
and migrate:
python manage.py schemamigration myapp --auto
python manage.py migrate myapp
I get django.db.utils.DatabaseError: relation "myapp.foo" already exists error.
I have already checked this question but --fake doesn't seem to be supported via South anymore.
Your models look invalid to me, though I'd be surprised if that's what's actually causing the problem.
It looks like your first argument is intended to be the verbose_name attribute, your model should probably look like this:
class Foo(models.Model):
value = models.TextField(verbose_name = u"Value")
live = models.BooleanField(verbose_name = u"Live", default=False)
creation_time = models.DateTimeField(verbose_name = u"Creation Time", auto_now_add=True, null=True, blank=True)
(you also forgot the u before the verbose_name for creation_time).
Meanwhile, --fake is definitely still supported (see the docs), what error are you getting when you try and run it?