models.py
def upload_to(instance, filename):
return 'verify/%s/%s' % (instance.user_idx.username, filename)
class UserVerifyImg(models.Model):
user_idx = models.ForeignKey(
User,
db_column='user_idx',
on_delete=models.CASCADE
)
business_type = models.CharField(max_length=255)
image = models.ImageField(upload_to=upload_to)
upload_date = models.DateTimeField(auto_now = True)
class Meta:
managed = False
db_table = 'account_user_verify'
This is my model. but It is showed me error.
account.models.UserVerifyImg.user_idx.RelatedObjectDoesNotExist: UserVerifyImg has no user_idx.
I don't now what is the problem. help me please.
Have you run migrations after changing in your model?
python manage.py makemigrations
Then:
python manage.py migrate
You are actually using the right query instance.user_idx.username the problem is that at the time you assigning the image path(upload_to) the instance is not created,so that means you can not get instance.user_idx.username that is why you are getting that exception.
To solve this problem you can create a foreignkey by doing something like this.
class UserVerifyImg(models.Model):
user_idx = models.ForeignKey(
User,
db_column='user_idx',
on_delete=models.CASCADE
)
business_type = models.CharField(max_length=255)
upload_date = models.DateTimeField(auto_now = True)
class Meta:
managed = False
db_table = 'account_user_verify'
def upload_to(instance, filename):
return 'verify/%s/%s' % (instance.user_verify_img.user_idx.username, filename)
class Image(models.Model):
user_verify_img = models.ForeignKey(UserVerifyImg,on_delete=models.CASCADE)
image = models.ImageField(upload_to=upload_to)
run python manage.py makemigrations
run python manage.py migrate
Note that You have to change your form and your views for this to work if you need more help let me know
Related
I got following error:
assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field )
Here is my Product class code:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="")
subcategory = models.CharField(max_length=50, default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateField()
image = models.ImageField(upload_to="shop/images", default="")
def __str__(self):
return self.product_name
What Am I doing wrong?
I have the same error, and i resolve doing that:
1 - Move to trash old migrate
2 - run python manage.py makemigrations
3 - run python manage.py migrate
if your problem persist, try to delete table into a data base ( if you do that, you lost your admin user, you can create another with python manage.py createsuperuser
I have made changes to one of my models in my project and migrate, makemigrations does not work as expected. Rebuilding the database creates only 2 out of 3 tables from my models.py and i cannot figure out the problem.
There are two different apps; "blog" and "users". both are registered in the setting.py.
I completely removed the database and deleted the migrations folders.
then i tried the following stuff:
django makemigrations blog
django migrate blog
doing a global django makemigrations does not have any effect, no changes are detected.
here is the relevant models.py of "blog":
class Room(models.Model):
roomname = models.CharField(max_length=6, unique=True)
roomeditors=models.ManyToManyField(User,related_name='rooms_user_can_edit', blank=True)
displayadmin=models.ForeignKey(User,
related_name='room_user_is_displayadmin',null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.roomname
class Post(models.Model):
title = models.CharField(max_length=40)
content = models.TextField(max_length=300)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
rooms = models.ManyToManyField(Room, related_name='roomposts', through='Display')
def __str__(self):
return self.title
def get_absolute_url(self):
return "/post/{}/".format(self.pk)
class Display(models.Model):
class Meta:
auto_created = True
post = models.ForeignKey(Post, on_delete=models.CASCADE)
room = models.ForeignKey(Room, on_delete=models.CASCADE)
isdisplayed = models.BooleanField(default=0)
def __str__(self):
return str(self.isdisplayed)
every table gets created except from display. the output is:
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model Room
- Create model Post
You are giving auto_created = True in your model's Meta class, which is not recommended neither its documented. Here is the list of all possible meta options you can give inside your model.
Official documentation says:
auto_created: Boolean flag that indicates if the field was automatically created, such as the OneToOneField used by model inheritance.
Giving this in Meta refrains Django to create this model itself.
When I go on localhost:8000/admin and click on "Quotes +ADD" it shows me error 500 instead of the editing interface. "Posts" works well. I just want to know if, without seeing the code, you could just tell me the different possible sources of this problem ?
EDIT: Here are models.py and admin.py:
models.py
class TimestampedModel(models.Model):
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
class Meta:
abstract = True
# Create your models here.
class Post(TimestampedModel):
title = models.CharField(max_length = 255, default='')
intro = models.TextField(default='')
title_one = models.TextField(default='')
text_one = models.TextField(default='')
title_two = models.TextField(default='')
text_two = models.TextField(default='')
title_three = models.TextField(default='')
text_three = models.TextField(default='')
def __repr__(self):
return self.title
class Quote(models.Model):
quote = models.TextField(default='')
author = models.CharField(max_length = 60, default='')
def __repr__(self):
return self.quote
admin.py
from django.contrib import admin
from .models import Post, Quote
# Register your models here.
admin.site.register(Post)
admin.site.register(Quote)
I also would like to let you know that when I try to make migrations and then migrate, it says "No changes detected".
ProgrammingError at /admin/blog/quote/
relation "blog_quote" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_quote"
I'll guess it might be OperationalError due to not running migrations for Quotes model.
Providing models.py and admin.py contents would make it much easier to debug though.
I am trying to add and "orders" field to a user that is a foreignkey to a class Order. Order has a foreignkey to a class OrderItem. OrderItem has a OneToOneField to another app's class Store Item. I used south to migrate the database. I do not believe the error is in the way the database was migrated. I get an operational error, "error: no such table: webstore_storeitem". Any help would be greatly appreciated. Thank you.
from django.contrib.auth.models import User
from django.db import models
from loginRouter import *
class OrderItem(models.Model):
itemCost = models.DecimalField(max_digits=16,decimal_places=2)
itemQuantity = models.IntegerField()
itemID = models.OneToOneField('webstore.StoreItem')
def __unicode__(self):
return self.itemID.itemName
class Order(models.Model):
orderDate = models.DateTimeField('Order Date')
shippingCost = models.DecimalField(max_digits=16,decimal_places=2)
totalCost = models.DecimalField(max_digits=16,decimal_places=2)
item = models.ForeignKey(OrderItem)
def __unicode__(self):
return unicode(self.item)
class UserProfile(models.Model):
user = models.OneToOneField(User)
confirmation_code = models.CharField(max_length=128)
reset_code = models.CharField(max_length=128)
address_lineOne = models.CharField(max_length=128)
address_lineTwo = models.CharField(max_length=128)
city = models.CharField(max_length=128)
State = models.CharField(max_length=128)
zipCode = models.CharField(max_length=10)
orders = models.ForeignKey(Order)
def __unicode__(self):
return self.user.username
What I did with south:
before Change:
$./manage.py schemamigration login --initial
after change:
$./manage.py schemamigration login --auto
$./manage.py migrate login --fake
$./manage.py migrate login
webstore.Models:
from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
class StoreCategory(models.Model):
categoryName = models.CharField(max_length=128)
def __unicode__(self):
return self.categoryName
class StoreItem(models.Model):
category = models.ForeignKey(StoreCategory)
itemName = models.CharField(max_length=128)
itemNameid = models.CharField(max_length=128)
description = models.CharField(max_length=2048)
price = models.DecimalField(max_digits=16,decimal_places=2)
quantity = models.IntegerField(default=0)
picture = ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(250, 185)],
format='JPEG',
options={'quality': 60})
featured_picture = ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(800, 300)],
format='JPEG',
options={'quality': 60})
isFeatured = models.BooleanField(default=False)
def __unicode__(self):
return self.itemName
The Problem was that each app was using a separate database. I merged them and this resolved the problem I was having.
I am having the following custom user model trying to use the Django 1.5 AbstractBaseUser:
class Merchant(AbstractBaseUser):
email = models.EmailField()
company_name = models.CharField(max_length=256)
website = models.URLField()
description = models.TextField(blank=True)
api_key = models.CharField(blank=True, max_length=256, primary_key=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['email','website']
class Meta:
verbose_name = _('Merchant')
verbose_name_plural = _('Merchants')
def __unicode__(self):
return self.company_name
The model works perfectly and database is as expected, but the problem is when I try to dumpdata to create fixtures for my tests.
python manage.py dumpdata --natural --exclude=contenttypes --exclude=auth.permission --indent=4 > fixtures/initial_data.json
Then I get the error:
CommandError: Unable to serialize database: <Merchant: Test Shop> is not JSON serializable
Do you have ideas what could be the reason for this. Could it be the charfield primary key or something with the abstractbaseuser model?
Thanks
After some time spend I found the problem. Actually it was not in Merchant model but in Product that has foreign key to Merchant:
class Product(models.Model):
name = models.CharField(max_length=200)
#merchant = models.ForeignKey(Merchant, to_field='api_key')
merchant = models.ForeignKey(Merchant)
url = models.URLField(max_length = 2000)
description = models.TextField(blank=True)
client_product_id = models.CharField(max_length='100')
objects = ProductManager()
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
unique_together = ('merchant', 'client_product_id',)
def __unicode__(self):
return self.name
def natural_key(self):
return (self.merchant, self.client_product_id)
the natural_key method in the model returned self.merchant instead of self.merchant_id so it was trying to serialize the whole merchant object to create a natural key. After switching the natural_key method to the following one the problem was fixed:
def natural_key(self):
return (self.merchant_id, self.client_product_id)