I just started learning Django yesterday, and I'm having a problem when I trying to add new tables to my MySQL server:
I created a model in models.py (lets say the app name is "article" and the model name is "Article"). I ran syncdb lots of times with different examples in the INSTALLED_APPS in the settings.py (like "article" and "article.models") but it doesn't add the tables.
(Of course I see the other tables like "auth_group", "auth_group_permissions" etc.. but not the table of the Article model I created.)
model.py:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date publish')
likes = models.IntegerField()
the project structure:
python version: 2.7.9
the db:
The documentation for the new Django migrations is available here:
https://docs.djangoproject.com/en/dev/topics/migrations/
once you have your new app and added it to INSTALLED_APPS in settings.py, you do the following:
python manage.py makemigrations
this will create a python file in the app migrations folder. It will realize the changes, new additions...etc to apply to your database and then you run
python manage.py migrate
no more syncdb, it will be obsolete soon
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 work on an online shopping website project with the help of Django. and I'm a beginner in Django The following code provides a table of my database. It helps to add a product.
class Product(models.Model):
category = models.ForeignKey(Category,related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=200,db_index=True)
slug = models.SlugField(max_length=200,db_index=True)
image = models.ImageField(upload_to='products/%y/%m/%d',blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.
OperationalError at /admin/onlineshop/product/add/
table onlineshop_product has no column named name
When I did migration using the command:
python manage.py migrate
It shows:
Operations to perform: Apply all migrations: admin, auth,
contenttypes, onlineshop, sessions Running migrations: No migrations
to apply. Your models in app(s): 'onlineshop' have changes that are
not yet reflected in a migration, and so won't be applied. Run
'manage.py makemigrations' to make new migrations, and then re-run
'manage.py migrate' to apply them.
python manage.py makemigrations
It is impossible to add the field 'created' with 'auto_now_add=True'
to product without providing a default. This is because the database
needs something to populate existing rows.
Provide a one-off default now which will be set on all existing
rows
Quit and manually define a default value in models.py. Select
an option:
How to solve it?
It is well-known issue, refer here[django-doc] for this, it will be easy if you choose 1st option.
Choose 1st option:
Then, you will be shown something like this in your shell:
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] >>>
Here, simply press Enter the field will be added to migration and your work is done then simply run migrate command. You can also check it in migration file.
Migration file
operations = [
migrations.AddField(
....
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
)
]
Edit:
Try this:
name = models.CharField(max_length=200,db_index=True,default='any_name')
Then run makemigrations and migrate.
Change your Product(...) class like this:
from django.db import models
from datetime import datetime
class Product(models.Model):
# ... all other fields
name = models.CharField(max_length=200, db_index=True, default='Name not provided')
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True, null=True)
and run these commands in sequence:
python manage.py makemigrations your_app_name # app name is optional parameter if you have app then provide app name
python manage.py migrate
Although settings null = True is bad idea but this will solve your problem for now but if you want to fix this issue you can follow this post or this answer.
Update
If above solution is not working or facing some issue then do like this:
Note : In this approach you've to delete you database (sqlite).
Step - 1
Delete __pycache__ & migrations folders from all of your apps
Step - 2
Delete db.sqlite3
Step - 3
Run makemigrations & migrate commands as mentioned above.
I am learning Django and I am using this tutorial:
https://www.youtube.com/watch?v=F5mRW0jo-U4&t=912s
I created an app called products and I have it in INSTALLED_APPS.
Upon creating a Product class in the models.py file in the products app folder, I created some fields such as price.
However, when I tried to use the makemigrations command, no changes detected was reported.
Folder Layout and Settings
models.py
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.TextField()
description = models.TextField()
price = models.TextField()
I checked if there were any issues with the Product class but there doesn't seem to be any as far as I can see, so I am at a loss as to why no changes were detected.
15
You may have deleted the migrations folder inside the app or init.py inside the /migrations/ folder, create a new one
myproject/ apps/
myapp/
migrations/
init.py
You can always do makemigrations seperately without doing the above step
python manage.py makemigrations myapp
Refer the table - djangomigrations .. if the entry is there for the makemigration file already in the table then trunckage and rerun makemigrations and then do migrate
I use to run my website on my laptop and its database was Sqlite, recently I wanted to transfer it to DigitalOcean and I changed its database to Postgresql, but when I migrate I encounters with some problems.
Python 3.4
Django 1.8
Error
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "profiles_userprofile"
My Model
class UserProfile(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(blank=True, upload_to=get_image_path, default='/static/image/avatar/male.png')
age = models.IntegerField(default=4, validators=[MinValueValidator(3), MaxValueValidator(99)])
What should I do?
Try explicitly specifying the id field and marking it as the primary key:
class UserProfile(models.Model):
id = models.BigIntegerField(primary_key = True)
user = models.OneToOneField(User)
avatar = models.ImageField(blank=True, upload_to=get_image_path, default='/static/image/avatar/male.png')
age = models.IntegerField(default=4, validators=[MinValueValidator(3), MaxValueValidator(99)])
Django should automatically create a sequence for this field.
It may be that the User foreign key without an explicitly defined primary key is confusing the ORM, although that's just a theory.
If you are developing locally, and don't care about your migration history, and you just need a quick-fix, you could do this:
manage.py migrate <your app name> zero
Then delete the migration files except for the __init__.py in <your app name>.
Finally:
manage.py makemigrations <your app name>
manage.py migrate
A more complicated approach would be learning how to write and modify migration files to populate existing rows.
learning django recently and ran into a problem with Django.
This is my models.py:
# -*- coding:utf-8 -*-
#/usr/bin/env python
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length = 100)
category = models.CharField(max_length=50,blank=True)
date_time = models.DateTimeField(auto_now_add=True)
content = models.TextField(blank=True,null=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['date_time']
first I input these in cmd:
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
but when, in the Django shell, I input this code:
from article.models import Article
Article.objects.create(title = 'Hello World', category = 'Python', content = 'what')
I received this error message:
OperationalErrors:no such table:article_ article
what's wrong?
thanks for your help
MAYBE something on migrations is not correct...
To create an app:
1) python manage.py migrate
2) python manage.py startapp myapp
3) add 'myapp', to INSTALLED_APPS in settings.py
4) create your model and save
5) python manage.py makemigrations myapp
6) python manage.py migrate myapp
You have to do the last two steps every time you change something in models.py.
Now some links: 1 2 and a very useful tutorial Django Girls
You can simply erase you db by deleting your db.sqlite
then ./manage.py syncdb.
If you don't want to loose your data then you need first, after making syncdb, run ./manage.py makemigrations, ./manage.py migrate.
Than, after changing your models you run ./manage.py makemigrations and ./manage.py migrate -these command will make necessary changes to DB schema.