Hi my code was running smoothly as i was following a tutorial but at a new step while adding new component in the model Order (processing, aprouved, refunbd_requested, refund_granted) the code crashed, the migrations operated but can't migrate i need help please.
my models.py
from django.conf import settings
from django.db import models
from django.shortcuts import reverse
from django_countries.fields import CountryField
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete= models.CASCADE)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
billing_address = models.ForeignKey('BillingAddress',
on_delete= models.SET_NULL, blank=True, null=True)
payment = models.ForeignKey('Payment',
on_delete= models.SET_NULL, blank=True, null=True)
coupon = models.ForeignKey('Coupon',
on_delete= models.SET_NULL, blank=True, null=True)
processing = models.BooleanField(default=False)
aprouved = models.BooleanField(default=False)
refund_requested = models.BooleanField(default=False)
refund_granted = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total(self):
total = 0
for order_item in self.items.all():
total += order_item.get_final_price()
if self.coupon:
total -= self.coupon.amount
return total
The last line of code for the error traceback after the migration, i try python manage.py migrate but i get that at the last line.
File "C:\Users\18094\AppData\Local\Programs\Python\Python37\lib\sitepackages\django\utils\dateparse.py", line 107, in parse_datetimematch = datetime_re.match(value)
The table might contain data that conflicts with the datatype, ie. one of your date fields.
Since this data is not critical, you can remove the data and start over.
assuming your app is named orders
./manage.py migrate orders zero # migrate to 0000, deleting the table
./manage.py migrate orders # migrate forward to current state
This method I am suggesting is a quick but not to recommend for the project in a production environment. You could try this out.
Make sure you add your app in the installed app, delete all your migrations folders, all the pycache folders, as well as the .sqlite file, then run the commands python manage.py makemigrations, python manage.py migrate and then start the server.
You could also run this python manage.py makemigrations app_name if the first command doesn't detect the migration
I hope this is helpful
Related
I tried to add a field to my ManyToMany relationship models in Django.
So step by step, I created the new model and apply makemigrations and migrate.
I checked I have the new table in my postgresql database.
Now before I will add the through keyword in the ManyToMany field I want to write a function in the migration file that will copy the old data of the previous ManyToMany table to the new one with the additional field.
I followed a solution explained here:
Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields
I want to test the function that will migrate the data in a test function but I don't understand what to do.
here my code:
survey/models:
class Survey(BaseModel):
name = models.CharField(max_length=256, help_text='Survey name')
user = models.ManyToManyField(User, blank=True, help_text='patient')
survey/models:
class SurveyStatus(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
survey_status = models.CharField(max_length=10,
blank=True,
null=True,
choices=STATUS_SURVEY_CHOICES,
)
The function I wrote that need to copy the data from the previous M2M to the new one is the following one:
def create_through_relations(apps, schema_editor):
Survey = apps.get_model('survey', 'Survey')
SurveyStatus = apps.get_model('survey', 'SurveyStatus')
for survey in Survey.objects.all():
for user in survey.user.all():
SurveyStatus(
user=user,
survey=survey,
survey_status='active'
).save()
I don't understand what is apps? because it is not recognized by python
I don't understand why i need schema_editor because it's not used
it doesn't recognized my Survey or SurveyStatus models too
when i tried to run this script with
if __name__ == "__main__":
create_through_relations(survey)
I've got this error
NameError: name 'survey' is not defined
and if i tried this function
from django.apps import apps
def create_through_relations():
Survey = apps.get_model('survey', 'Survey')
SurveyStatus = apps.get_model('survey', 'SurveyStatus')
for survey in Survey.objects.all():
for user in survey.user.all():
SurveyStatus(
user=user,
survey=survey,
survey_status='active'
).save()
when i tried to run this script with
if __name__ == "__main__":
create_through_relations()
I've got this error
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
If someone can help and explain me how to solve.thanks
1: Apps represent the different parts of your project (Django Apps)
2: You don't need it at this point. In general, it translates the models into SQL syntax.
3: python manage.py <...> does load the models for execution. Your file is trying to access data that isn't available that way.
4: The variable survey can't be found in python's main function, since you never declared it there. You need to trigger it inside your project.
5: You can test things by creating a test.py (Django Tests)
6: You don't need to transfer the data to a whole new table after changing a model, just extend the existing one and migrate the changes:
class BaseModel(models.Model):
created = models.DateTimeField('created', default=timezone.now)
changed = models.DateTimeField('changed', default=timezone.now, blank=True, null=True)
class Survey(BaseModel):
uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=256, help_text='Survey name')
description = models.TextField('description', blank=True)
status = models.BooleanField(default=False) # paused/ active
class SurveyQuestion(BaseModel):
survey = models.ForeignKey(Survey, related_name='survey', on_delete=models.CASCADE)
text = models.CharField(max_length=256)
# 1 -> Text, # Integer, # ChoiceField, etc.
requested_result = models.IntegerField(default=0)
class QuestionResult(BaseModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
question = models.ForeignKey(SurveyQuestion, related_name='survey_question', on_delete=models.CASCADE)
answer = models.CharField(default='', max_length=256)
I'm new to Django, and I'm trying to create a "game" model with two attributes:
A many-to-one field where multiple instances of the game model are associated with an instance of a custom user model.
A many-to-many field where instances of the game model are connected with multiple instances of words, and instances of the word model are connected with multiple instances of the game model
Top of my models.py model:
from django.db import models
from users.models import CustomUser
from django.contrib.postgres.fields import ArrayField
Game model:
class SortingGame(models.Model):
user_current_player = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
field_words = models.ManyToManyField(Word, related_name="field_sorting_games")
Word model:
class Word(models.Model):
str_word = models.CharField(max_length=50,null=True)
int_grade_level = models.IntegerField()
arrint_phonemes = ArrayField(models.CharField(max_length=50),null=True)
arrstr_graphemes = ArrayField(models.CharField(max_length=50),null=True)
int_num_syllables = models.IntegerField()
arrstr_syllables = ArrayField(models.CharField(max_length=50),null=True)
User model:
class CustomUser(AbstractBaseUser):
# must have the following fields for django
email = models.EmailField(verbose_name="email",max_length = 100,unique=True)
username = models.CharField(max_length = 30, unique = True)
date_joined = models.DateTimeField(verbose_name = "date_joined",auto_now_add=True)
last_login = models.DateTimeField(verbose_name = "last_login",auto_now = True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default = False)
is_staff = models.BooleanField(default = False)
is_active = models.BooleanField(default = True)
first_name = models.CharField(max_length=15, blank=True)
last_name = models.CharField(max_length=30, blank=True)
spelling_level = models.IntegerField(default=1, unique=False)
time_played = models.IntegerField(default=0, unique=False)
percent_correct = models.IntegerField(default=0, unique=False)
admin.py:
from django.contrib import admin
from .models import Word, SortingGame
admin.site.register(SortingGame)
When I run python3 manage.py makemigrations and python3 manage.py migrate, it doesn't complain, but when I go to the admin page of my django site it says psycopg2.errors.UndefinedColumn: column "user_current_player_id" of relation "game_sortinggame" does not exist.
This makes me think the issue is with user_current_player in SortingGame (it worked fine before I added that attribute), but I've looked around on different forums to see what might be going wrong and I can't seem to figure it out. I tried starting from scratch with a new database, and it's still throwing the same exception. Any ideas would be appreciated—thanks!
Nathan!
First thing would be make sure that you have the app where CustomUser model is created in your settings.py file, at INSTALLED_APPS.
If so, please have a look at this folder (app) where you have CustomUser defined to verify if there is in deed a migrations folder there.
I suspect that Django in not aware of this app (not under INSTALLED_APPS) and therefore did not migrated it. So, your database is not finding the User Model connection.
That said, I would suggested you to keep your account model as defined by Django User and create another model with a direct relationship to it to deal with profile/game fields such as spelling level, percentage_correct and so on.
This would keep your Model "concerns" more organized later on.
if you did make a migrations before try to use (python manage.py makemigrations -appname)
Also after That you need to Add the module in your admin.py
from django.contrib import admin
from .models import *
admin.site.register(SortingGame)
... all other modules
I have a below model,
class PersonIndustry(DFModel):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
industry = models.CharField(max_length=50, blank=True, null=True)
class Meta:
db_table = ‘person_industry'
My postgres database contains person_industry table.
When I registered this model in admin site it is giving me below error,
ProgrammingError at /admin/apis/personindustry/
relation "personindustry" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM “personindustry"
I am quite confuse why it is searching for personindustry instead of person_industry. Please advise.
I also had this problem recently, what I did is:
# Clear migrations history
python manage.py migrate --fake APP_NAME zero
Then, delete the migrations files and .pyc files except for init.py. Now, make migrations:
python manage.py makemigrations APP_NAME
Now, fake the intial migrate. That will fake the intial table with name personindustry:
python manage.py migrate --fake-initial
*Note:- Feel free to ask. Refs
My meta class was creating problem,
class DFModel(models.Model, metaclass=DFModelBase):
class Meta:
abstract = True
I changed it to default,
class PersonIndustry(models.Model):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
industry = models.CharField(max_length=50, blank=True, null=True)
class Meta:
db_table = ‘person_industry'
It is loading now.
I extend the Django user model like this:
#core.models
class Institute(models.Model):
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message=institute_phone_help_text)
name = models.CharField(_('name'), max_length=255)
description = models.TextField(_('description'), blank=True)
abbreviation = models.CharField(_('abbreviation'), blank=True, max_length=100)
address = models.TextField(_('address'), blank=True)
phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
websites = ArrayField(models.URLField(max_length=255), verbose_name=_('websites'), blank=True, null=True)
class Meta:
verbose_name = _('institute')
verbose_name_plural = _('institutes')
def __str__(self):
return '{0} ({1})'.format(self.name, self.abbreviation)
class User(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
institute = models.ForeignKey(Institute, on_delete=models.CASCADE)
params = JSONField(_('params'), null=True, blank=True,)
about_me = models.TextField(_('about me'), blank=True,)
With an empty DB each time that I launch ./manage.py makemigrations core it creates always a new migration file
import django.contrib.auth.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20190430_1655'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
I tried different combinations:
./manage.py makemigrations core
./manage.py migrate core
./manage.py migrate
./manage.py makemigrations core
./manage.py makemigrations core
./manage.py makemigrations
./manage.py migrate
It always creates the migration file.
Thanks.
D
if you use AbstractUser model make sure you run makemigrations before migrate.
i had same issue with AbstractUser,
I solved it by deleting the sqlite3 file also all migrations files.
After that i run this two commands :
python manage.py makemigrations
python manage.py migrate
inside your terminal
Let me know if that help!
So using south, I wanted to add a new field is_private to one of my models.
Following the tutorial, after changing the models.py file, I should do this:
./manage.py schemamigration reconstructions --auto
which returns:
Added field is_private on reconstructions.Reconstruction
Created 0005_auto__add_field_reconstruction_is_private.py. You can now apply this migration with: ./manage.py migrate reconstructions
Which is great. Now next step is,
python manage.py migrate reconstructions
And that prints:
- Migrating forwards to 0005_auto__add_field_reconstruction_is_private.
> reconstructions:0005_auto__add_field_reconstruction_is_private
- Loading initial data for reconstructions.
No fixtures found.
it seems to be doing it's job. But when I afterwards check the field is_private, Django throws me an error:
Cannot resolve keyword 'is_private' into field.
Which tells me south did not changed the database at all. Why is so?
Extra information:
The model class:
class Reconstruction(models.Model):
id = models.CharField(max_length=36, primary_key=True,
editable=False)
uploader = models.ForeignKey(User, blank=True, null=True)
status = models.TextField(blank=True)
viewcount = models.IntegerField(default=0)
error_flag = models.IntegerField(default=0)
is_done = models.BooleanField(default=False)
create_date = models.DateTimeField(auto_now=True)
last_modified_date = models.DateTimeField(auto_now=True)
is_private = models.BooleanField(default=True)
The code causing the crash:
recordings = Recording.objects.filter(is_done=True).filter(is_private=False).order_by('-create_date')
Observation: you added is_private to Reconstruction, but you're trying to filter Recording objects based on that property. Perhaps this is the issue?