I'm working on this project and i'm extending Django's base user model in order to have emails as usernames. I've got the following project structure with two apps (client and showroom)
. project
.. client
... models
.... Client
.. showroom
... models
.... Image
Client inheritates AbstractBaseUser like this:
class Client(AbstractBaseUser):
email = models.CharField(max_length=255, unique=True)
firstname = models.CharField(max_length=50)
etc...
Image has a Foreign Key to my Client model:
class Image(models.Model):
client = models.ForeignKey(_('Client'), settings.AUTH_USER_MODEL, blank=True, null=True, limit_choices_to=Q(groups__name = 'website_user'))
etc...
And in my settings.py (which is not called settings.py, don't think it's relevant but just in case) I have got this:
INSTALLED_APPS = (
'django.contrib.auth',
etc...
'client',
'showroom',
etc...
)
AUTH_USER_MODEL = 'client.Client'
Now, when I try to run the project, syncdb, migrate or whatever else that has to do with the database, I get this error:
showroom.Image.client: (fields.E300) Field defines a relation with model 'Client', which is either not installed, or is abstract.
Of course, when I remove the foreign key to Client in my Image model, everything works fine.
I have googled this a lot and most solutions suggest that my apps are not properly installed, but they seem to be as shown in my config file. So I guess this has something to do with inheriting django's AbstractBaseUser, but i can't see why this wont work for me, as my code is very similar to the one in the official docs.
Anyway, thanks in advance for your help.
First argument of ForeignKey should be a model or a name of a model. You pass _('Client') what I think is verbose_name.
Try this:
client = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Client'), blank=True, null=True, limit_choices_to=Q(groups__name = 'website_user'))
Related
I'm building a simple recipe app, and so far I have two models: Ingredient and Recipe.
Each recipe should have multiple ingredients, so I laid out my model like this:
class Ingredient(models.Model):
name = models.CharField(max_length=50)
class Recipe(models.Model):
title = models.CharField(max_length=100)
ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE)
instructions = JSONField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon')
When I makemigrations, I get nothing, but when I migrate, I get this ValueError:
ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?)
Following the example here (Django: Add foreign key in same model but different class), I've tried setting ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE) as well as using lazy syntax ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE), but each time, makemigrations shows no changes, and migrate gives me the same ValueError.
Edit
My imports:
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.fields.json import JSONField
from django.utils import timezone
from django.contrib.auth.models import User```
Try replacing on_delete=CASCADE with on_delete=models.CASCADE
If you have not imported CASCADE separately from models.
All though, in that case you should get a warning that "CASCADE is not defined".
I believe I found the problem: My models.py file was in the root directory, not in the app directory.
My English is poor, sorry
This is my struct:
bookstore
---author(app1)
---book(app2)
Or in code:
from django.db import models
from author.models import Profile
from django.contrib import admin
class Book(models.Model):
title = models.CharField(max_length = 150)
page = models.IntegerField()
price = models.IntegerField()
author = models.ForeignKey(
'Profile',
on_delete=models.CASCADE,)
publish_date = models.DateField()
class Meta(object):
db_table = "book"
class BookAdmin(admin.ModelAdmin):
pass
admin.site.register(Book, BookAdmin)
mysql have some data, now I want to use them to show my web, not to do that creat data in database. Thank you guys!
I have a question:
My Django == 1.9 , python == 3 , windows10
I want to use mysql (my database contect is really do it).
When I find some resource, I will see that
python manage.py sql [appname] it is Django to SQL
when I want to use Django to mysql.
Can I use python manage.py inspectdb? It will have a models.py
python manage.py sql [appname] = python manage.py inspectdb?
ERRORS:
book.Book.author: (fields.E300) Field defines a relation with model 'Profile', which is either not installed, or is abstract.
book.Book.author: (fields.E307) The field book.Book.author was declared with a lazy reference to 'book.profile', but app 'book' doesn't provide model 'profile'.
In your Book model, you refer with a field named author to a model Profile. Since that model is defined in another app, you should refer to it as app_name.ModelName, so likely that is:
class Book(models.Model):
title = models.CharField(max_length = 150)
page = models.IntegerField()
price = models.IntegerField()
author = models.ForeignKey(
'app1.Profile', # add name of the app
on_delete=models.CASCADE,
)
publish_date = models.DateField()
If you named this model Author however, as the question text (not the code), seems to suggest, you should use app1.Author. Of course you replace app1 with the real name of the app.
This is described in the documentation in the ForeignKey [Django-doc]:
To refer to models defined in another application, you can
explicitly specify a model with the full application label. For example, if the Manufacturer model above is defined in another
application called production, you’d need to use:
class Car(models.Model):
manufacturer = models.ForeignKey(
'production.Manufacturer',
on_delete=models.CASCADE,
)
I am trying to use Cookiecutter to help me to deploy a web app with Heroku and Amazon S3.
This is an app that I developed locally without Cookiecutter so I am copy-pasting the files into the new project and debug step by step.
The original app used the build-in Django User Model so I would like to switch to the Abstract User Model that comes with Cookiecutter.
I started to create a new database for this project to start from scratch.
Then I thought it would be as simple as replacing User by AUTH_USER_MODEL
models.py
from config.settings.base import AUTH_USER_MODEL
class Category(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=140,blank=True,null=True)
date_created = models.DateField(default=timezone.now)
date_updated = models.DateField(auto_now=True)
created_by = models.ForeignKey(AUTH_USER_MODEL, related_name="categories")
def __str__(self):
return self.name
I get this error when running manage.py migrate
accounts.User.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'
In settings.py
AUTH_USER_MODEL = 'users.User'
Where I am missing something ?
Your error message seems to indicate that the problem is coming from another model called accounts.User, but it's not included in the snippet you provide. The error shows a model in the accounts app but the setting AUTH_USER_MODEL points to a model in the users app. Are these 2 different models? Did you rename the users app as accounts but forgot to update the setting?
I have 5 models in one of my apps
Report ReportData Customer ..etc
For some reason, ever since my last deployment, I can no longer change or create new Report or Customer objects, but everything else works? Any idea why this would be happening? The admin page just outputs nothing on the add link and the change link outputs nothing as well.
Django==1.9.1
I have tried restarting servers, running migrations, and restarting database. The development version works fine. Such a strange problem.
As you can see, there are no fields even though this object has been populated with tons of data in the database.
Here is my Report model:
class Report(models.Model):
public_uuid = models.UUIDField(max_length=256,default=util.make_uuid,unique=True)
customer = models.ForeignKey('Customer')
has_payed = models.BooleanField(default=False)
#... etc
Here is how I register items in the admin:
admin.site.register(Customer)
admin.site.register(Report)
admin.site.register(...etc)
The other 3 models I have work fine. The only difference between these two models and the other three (that work and are editable with the admin tool) is that these two models have #property and #staticmethod methods attached to them.
Just had this issue
When using auto_now_add=True or editable=False in the field definition, the admin will not show the corresponding fields unless you specify them in the readonly_fields of the admin form definition.
if in models.py
class TransmissionLog(models.Model):
dataSource = models.ForeignKey(Browser, editable=False)
dateCreated = models.DateTimeField(auto_now_add=True, editable=False)
then admin.py needs
class TransmissionAdminManager(admin.ModelAdmin):
readonly_fields = ['dataSource', 'dateCreated']
admin.site.register(TransmissionLog, TransmissionAdminManager)
I have two models, and a relation between them:
class Person(models.Model):
name = models.CharField(max_length=10)
class Publication(models.Model):
name = models.CharField(max_length=10)
authors = models.ManyToManyField('Person', through='PublicationPersonMembership')
class PublicationPersonMembership(models.Model):
author=models.ForeignKey('Person')
publication = models.Foreignkey('Publication')
is_author = models.BooleanField()
The code above works and syncs without problem. I have defined then a model admin for the Publication class:
class PublicationAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': ('name', )}),
(_('Extra'), {'fields': ('authors',)})
)
I have a problem with the admin then: in localhost (django development server) I am getting a validation error as follows:
ImproperlyConfigured: 'PublicationAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.
That's ok, I can cope with that although I would like to override this problem. But, here comes my real doubt, when I deploy this code on an Apache+WSGI server I don't get any error and the code runs smoothly. Why? Is there any difference in django validation depending on the stack?
Thanks in advance!
It seems that the validation framework is not run automatically in production environments (apache + wsgi or equivalent).