Updating new fields in my model - python

I'm trying to update new fields in my db about my "card" model that already had fields above, but I have a problem that impede me do this process:
When I ran ./manage.py syncdb I got this message:
Your models 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.
So I ran makemigrations command but...
You are trying to add a non-nullable field 'imagen' to card without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
I chose press the second option and add the requirement myself, actually I have this:
models.py:
from django.db import models
class subscriber(models.Model):
nombre = models.CharField(max_length=200)
apellidos = models.CharField(max_length=200)
status = models.BooleanField(default=True)
def __unicode__(self):
nombreCompleto = "%s %s"%(self.nombre,self.apellidos)
return nombreCompleto
def url(self,filename):
ruta = "MultimediaData/Card/%s/%s"%(self.nombre,str(filename))
return ruta
class card(models.Model):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
imagen = models.ImageField(upload_to=url)
precio = models.DecimalField(max_digits=6,decimal_places=2)
stock = models.IntegerField()
def __unicode__(self):
return self.nombre
If I modify "Imagen" Field like said the message I would do as follows:
imagen = models.ImageField(upload_to=url, default='')
But then the same message appear after having made ​​the same modification to "imagen" field:
You are trying to add a non-nullable field 'precio' to card without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
And finally this last:
You are trying to add a non-nullable field 'stock' to card without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
If I modify all these fields, I finally can run ./manage.py makemigrations:
Migrations for 'synopticup':
0002_auto_20141016_2004.py:
- Add field imagen to card
- Add field precio to card
- Add field stock to card
But when I run ./manage.py syncdb I obtain this error:
django.core.exceptions.ValidationError: [u"'' value must be a decimal number."]
What's wrong with my process? I prefered leave all as they were before:
class card(models.Model):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
imagen = models.ImageField(upload_to=url)
precio = models.DecimalField(max_digits=6,decimal_places=2)
stock = models.IntegerField()
apologizeme in advance my extensive question and if I overlook something.
Thanks!!

The default for a DecimalField should be a Decimal object.
from decimal import Decimal
class card(models.Model):
# ...
imagen = models.ImageField(upload_to=url, default='')
precio = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal(0))
stock = models.IntegerField(default=0)

Related

It is impossible to add a non-nullable field 'id' to video without specifying a default

This is my models.py
from ast import Delete
from email.policy import default
from django.db import models
from django.contrib.auth.models import User
class Video(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title=models.CharField(max_length=100, null=False)
description=models.TextField(max_length=1000,null=True)
video=models.FileField(upload_to="video/%y",null=False)
def __str__(self):
return self.title
class Euser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=10,null=True)
birthdate = models.DateField(null=True,)
profile_pic = models.ImageField(null=True, )
cover_pic = models.ImageField( null=True, upload_to="images/%y")
def __str__(self):
return self.phone
when i try to makemigrations
It is impossible to add a non-nullable field 'id' to video without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:
Provide a one-off default now (will be set on all existing rows with a null value for this column)
Quit and manually define a default value in models.py.
This error occurs...
Please suggest me what should i do
and also suggest me about any changes in model
For a particular model, in the database, if records already exist and add new fields to the model then it shows such an error. To overcome this problem, you have to set the new field as blank=True and null=True or you can set some default value to the new field using default='some_value'.

django: how to update models

I want the update a model in django
this is a model in models.py:
class Article(models.Model):
CATEGOTY = (
('programming', 'programming'),
('other', 'other')
)
title = models.CharField(max_length=100, null=False)
content = models.TextField(null=False)
category = models.CharField(max_length=100, choices=CATEGOTY, null=False)
creation = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
def __str__(self):
return self.title
for example i want to add slug in this model like this:
slug = models.SlugField(max_length=100, null=False)
but when i display py manage.py makemigrations; this is shown to me:
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
what should I enter if I select option 1?
if i type datetime.date.today() It gives me an error that says:
TypeError: function missing required argument 'year' (pos 1)
When you add a mandatory field when the table is not empty, you need to provide the system with information to populate the new field.
For this, you have 2 choices:
define a rule for a default value
choose option 2 and, for each row, you will be asked to enter a value
For option 1, maybe you should use slugify() function (from django.utils.text module)
What I do sometimes is add the rule in the model's definitioon, to ensure existing rows will be updated, then I remove the constraints and manage values by the application.
You can delete your previous migrations then try to migrate again I think it will do the work. but the problem is it will delete all the records.

How to insert data into a relational one to one table in django?

I have a UserProfile table which is in relation with the default Django User table. Here's how it looks.
class UserProfile(models.Model):
user = user.OneToOneField(User, on_delete=models.CASCADE)
section = models.CharField(max_length=255, blank=True)
year = models.IntegerField(null=True, blank=True)
course = models.CharField(max_length=255, blank=True)
qrcode = models.CharField(max_length=255, blank=True)
present = models.BooleanField(default=False)
I am trying to insert the data into the UserProfile table using the Django Shell.
from users.models import UserProfile
a = UserProfile(qrcode="hello")
a.save()
This is how I have always known to insert data into tables, it has always worked. BUT when i try to do this in UserProfile model. I get this exception. NOT NULL constraint failed: users_userprofile.user_id. Which in turn is caused by the following exception Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
I somewhat understand that I somehow need to supply a user instance. But I am clueless as to how. Can someone please help me.
Firstly you need to create User.
u1 = User(username='user1')
u1.save()
Create a UserProfile. Pass the ID of the “parent” object as this object’s ID:
v1 = UserProfile(user=u1, ....)
v1.save()
refer this
You need to create your User first
user = User.objects.create(username='user')
and then you can do:
user_profile = UserProfile.objects.create(user=user, ...)

Multiple default values specified for column "uid" of table in Django 1.8

I am creating a Django Application, and my models.py is :
class Registration(models.Model):
uid = models.AutoField(primary_key=True, default=0)
uname = models.CharField(max_length=100, blank=False, null=False)
upassword = models.CharField(max_length=100, blank=False, null=False)
uphone = models.IntegerField(blank=True, null=True)
uhid = models.ForeignKey('Hood', blank=False, null=False, default='ABC')
uemail = models.EmailField(blank=False, null=False, default='abc402#nyu.edu')
uintro = models.TextField(null=True, blank=True)
uphoto = models.ImageField(upload_to='', blank=False, null=False, default='static/img/natural_join_is_inner_join.png')
uhood = models.CharField(max_length=10, null=True)
uaddress = models.CharField(max_length=100, default='ABC')
# django automatically uses the media root which you have declared in your settings, define that to `upload_to`
def __unicode__(self):
return self.uname
I then run the following commands:
python manage.py makemigrations
python manage.py migrate
But it is showing me an error:
multiple default values specified for column "uid" of table
"registration_registration"
Can anyone help me to resolve this issue? The other links on stack overflow are not of much help!
When I removed id uid field then Django is showing me:
You are trying to add a non-nullable field 'id' to registration without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
The issue is why I should provide a default value for id which django automatically creates?
UPDATE: I have deleted the migration folder, so I was resolve the above issue but now I am getting an error:
"Error creating new content types. Please make sure contenttypes "
RuntimeError: Error creating new content types. Please make sure
contenttypes is migrated before trying to migrate apps individually.
You should not have defined a default value for uid in the first place. It's an AutoField, it gets an auto-incremented value from the database.

Using model inheritance and encounting by non-nullable field error

I used inheritance model in my project after changing the model; but I give non-nullable field error. What should I do?
I am using Django 1.7
class Questions(models.Model):
question_category = models.ForeignKey(Course, blank=False)
question_author = models.ForeignKey(Author, blank=False)
question_details = models.CharField(max_length=100, blank=False, default='')
timestamp = models.DateTimeField(auto_now_add=True)
class TypeFive(Questions):
question_title = models.CharField(max_length=100, blank=False, default=generator(5), unique=True, editable=False)
def __str__(self):
return "{}".format(self.question_title)
class TypeFiveChoice(models.Model):
question_choice = models.ForeignKey(TypeFive)
is_it_question = models.BooleanField(default=False)
word = models.CharField(default='', blank=False, max_length=20)
translate = models.CharField(default='', blank=False, max_length=20)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "{} : {}, {}".format(self.question_choice, self.word, self.translate)
After migrations:
You are trying to add a non-nullable field 'questions_ptr' to typefive without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
In order to inherit from Questions in TypeFive, Django needs to add a relation from TypeFive to Questions. For all records in TypeFive that might already be in the database.
Django now doesn't know which question it should relate TopFive to. This is what the migrate command asks you for. You have a few options, but they greatly depend on your use case and whether you are in early development or if there is a production database where this migration has to run later.
I'm in early development and running it on localhost, so iI don't care
about my records. Now, what should I do?
In this case you haven't much to worry about, when migrate asks you type 1 and then press enter. Now add a primary key of a Questions instance that is in your database and then hit enter again.
Django now relates all TypeFive instances that are currently in the database to this question, so you might have to clean that up afterwards (e.g. by editing the TypeFive in Django admin).
#Nick Brady pointed this out in the question above so I don't mean to take credit but I wanted to highlight.
If your new inheritance class is only used for the purpose of being inherited from, you can easily get around this by setting your parent class to abstract.
class Parent(models.model):
Name = models.CharField(max_length=50)
class Meta:
abstract = True
class Child(Parent):
foobar = models.CharField(max_length=50)
class Meta:
db_table = "typenex_taxonomy_nodes"

Categories