I have a Django app that works perfectly on google app engine, using the datastore via djangae. However, the admin site throws an error:
NotSupportedError at /admin/auth/user/5629499534213120/change/
Cross-join where filters are not supported on the Datastore
This error only occurs when trying to edit the default Django user model. Not sure why this is happening.
I have used the default Django user model. (this is an app dealing with donations for a nonprofit)
models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class FoodSplashUser(models.Model):
base_user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.TextField(null=True)
city = models.TextField(null=True)
state = models.CharField(max_length=4, null=True)
zip = models.CharField(max_length=10, null=True)
def __str__(self):
return str(self.base_user.username)
class Organization(models.Model):
base_user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.TextField(null=True)
city = models.TextField(null=True)
state = models.CharField(max_length=4, null=True)
zip = models.CharField(max_length=10, null=True)
description = models.TextField(null=True)
image_url = models.URLField(null=True)
def __str__(self):
return str(self.base_user.username)
class DonationRequest(models.Model):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
request_type = models.TextField(null=True)
description = models.TextField(null=True)
def __str__(self):
return str(self.organization.base_user.username) + " " + self.request_type
class DonationPromise(models.Model):
user = models.ForeignKey(FoodSplashUser, on_delete=models.CASCADE)
donation_request = models.ForeignKey(DonationRequest, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
verified = models.BooleanField(default=False)
def __str__(self):
return str(self.user.base_user.username) + " " + str(self.donation_request)
This app goes with the default Django admin interface, but I decided to make the classes below for easy editing later.
admin.py:
from django.contrib import admin
from . import models
# Register your models here.
class FoodSplashUserAdmin(admin.ModelAdmin):
pass
class OrganizationAdmin(admin.ModelAdmin):
pass
class DonationRequestAdmin(admin.ModelAdmin):
pass
class DonationPromiseAdmin(admin.ModelAdmin):
pass
admin.site.register(models.FoodSplashUser, FoodSplashUserAdmin)
admin.site.register(models.Organization, OrganizationAdmin)
admin.site.register(models.DonationRequest, DonationPromiseAdmin)
admin.site.register(models.DonationPromise, DonationPromiseAdmin)
This may be a separate error, but :
admin.site.register(models.DonationRequest, DonationPromiseAdmin)
admin.site.register(models.DonationPromise, DonationPromiseAdmin)
Shouldn't that first one be: DonationRequestAdmin?
NotSupportedError indicates that your code performs an action that is not possible with App Engine Datastore. Not all the Django ORM features can be used in a non-relational database which Datastore is. You are trying to create an entity that has some relations, which causes the error. Probably it is a good idea to use Gauth for authentication and user management, as described in the Djangae docs.
Related
In My Django Project, there are two apps: Login and Company
The error that am receiving in this is
AttributeError: module 'login.models' has no attribute 'Country'
Company App > models.py
from django.db import models
from login import models as LM
class CompanyProfile(models.Model):
full_name = models.CharField(max_length=255,
unique = True)
country = models.ForeignKey(LM.Country,
on_delete=models.SET_NULL,
null=True,
blank=False)
state = models.ForeignKey(LM.State,
on_delete=models.SET_NULL,
null=True,
blank=False)
def __str__(self):
return self.full_name
Login App > models.py
class Country(models.Model):
"""List of Country"""
name = models.CharField(max_length=50, unique= True, default='None')
code = models.CharField(max_length=2, unique= True, primary_key=True, default ='NA')
def __str__(self):
return str(self.code)
class State(models.Model):
"""List fo State"""
region = models.CharField(max_length = 255, unique = True, primary_key=True, default='None')
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=False, default ='NA')
def __str__(self):
return self.region
Here is test to check that weather is login is getting imported or not
def test_import():
try:
# import pdb; pdb.set_trace()
importlib.find_loader('LM.Country')
found = True
except ImportError:
found = False
print(found)
Answer is received stands to be True
python3 manage.py shell
>>> test_import()
True
Now on other stackoverflow blogs i checked i thought it could be of Circlular Import
But i have already fixed that still am getting this error?
Thanks in Advance
Regards
I am not able to see any issue here technically. Maybe Django doesn't support this alias way of mentioning model as Foreign Key which I have never tried this way.
But I would suggest to use string format for adding Foreign Key of other model as below.
class CompanyProfile(models.Model):
full_name = models.CharField(max_length=255, unique = True)
# In following line, as I mention model name in string which django understands
country = models.ForeignKey('login.Country', on_delete=models.SET_NULL,
null=True,blank=False)
Another way is simple import but it might be a problem in case of circular depedencies. So I don't recommend to use that.
I hope you get the answer out of it.
The idea is super simple. This is specific to my project, I want to add data to 2 objects of the same model on one Django admin page and have one save button.
My class:
class Data(models.Model):
issuer = models.ForeignKey(Issuers, on_delete=models.CASCADE)
issuer_field = models.ForeignKey(Fields, on_delete=models.CASCADE, null=True)
data_year = models.PositiveSmallIntegerField()
long_term_ar = models.IntegerField()
section_1 = models.IntegerField()
short_term_ar = models.IntegerField()
short_term_investments = models.IntegerField()
cash = models.IntegerField()
To illustrate:I want to have 2 of those on the same page
I am new to Django, and it will be super helpful if you will help me implement this idea
Take a look on "Inlinemodeladmin objects": https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#inlinemodeladmin-objects
You will be able to add more than one record at the same time:
Try this approach. I am still learning Django too. However, I believe that you dont need to specify the save instance since it is already built in django.
models.py
class Data(models.Model):
issuer = models.ForeignKey(Issuers, on_delete=models.CASCADE)
issuer_field = models.ForeignKey(Fields, on_delete=models.CASCADE, null=True)
data_year = models.PositiveSmallIntegerField()
long_term_ar = models.IntegerField()
section_1 = models.IntegerField()
short_term_ar = models.IntegerField()
short_term_investments = models.IntegerField()
cash = models.IntegerField()
admin.py
from django.contrib import admin
from .models import Data
class DataAdmin(admin.ModelAdmin):
list_display = ('issuer', 'issuer_field')
admin.site.register(Data)
I'm trying to model a rent contract in Django and use the admin form to insert and modify it.
Both owner and tenant can be companies (VAT number) or individuals (no VAT number). Companies and individuals are stored in two different models (Company and Individual).
I'm trying to solve this problem using Generic Foreign Key but I'm not able to show the tenant name in the admin page, only an integer field not friendly at all.
gestimm is the name of the app and that's my oversimplified models:
# my gestimm/models.py
#
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Individual(models.Model):
name = models.CharField(max_length=100, help_text='Name')
def __str__(self):
return self.name
class Company(models.Model):
name = models.CharField(max_length=100, help_text='Name')
def __str__(self):
return self.name
class Contract(models.Model):
description = models.CharField(max_length=30)
start = models.DateField()
stop = models.DateField()
def __str__(self):
return self.description
class Tenant(models.Model):
limit = models.Q(app_label='gestimm', model='individual') | models.Q(app_label='gestimm', model='company')
contract = models.ForeignKey(Contract, on_delete=models.CASCADE,
null=True, blank=True)
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT,
help_text='Tenant', null=True,
limit_choices_to=limit)
object_id = models.PositiveIntegerField(null=True)
tenant = GenericForeignKey('content_type', 'object_id')
How I tried to solve the problem:
# my gestimm/admin.py
#
from django.contrib import admin
from .models import Individual, Company, Contract, Tenant
class TenantInline(admin.StackedInline):
model = Tenant
extra = 1
class ContractAdmin(admin.ModelAdmin):
inlines = [TenantInline]
admin.site.register(Individual)
admin.site.register(Company)
admin.site.register(Contract, ContractAdmin)
I found some old discussions but none of the proposed solutions worked.
Problem solved: I installed django-grappelli.
My new admin.py:
class TenantInline(admin.TabularInline):
model = Tenant
extra = 1
related_lookup_fields = {
'generic': [['content_type', 'object_id']],
}
class ContractAdmin(admin.ModelAdmin):
inlines = [
TenantInline,
]
admin.site.register(Contract, ContractAdmin)
As intended
Hi i have a django model for notification which have a many-to-many relation but nothing appears in django admin ( all fields do not appear)
class Notification(models.Model):
"""send notification model"""
title = models.CharField(max_length=200)
text = models.TextField(null=True, blank=True)
device = models.ManyToManyField(Device, null=True, blank=True)
country = models.ManyToManyField(Country, null=True, blank=True)
sent = models.BooleanField(default=False)
when i open django admin for this model and press add notification this is what happens (nothing appears)
Country and Device Code
class Device(models.Model):
"""Store device related to :model:`accounts.User`."""
user = models.OneToOneField(User, related_name='device', on_delete=models.CASCADE)
model = models.CharField(max_length=200, blank=True, null=True)
player_id = models.CharField(max_length=200, blank=True, null=True)
class Meta:
verbose_name = 'Device'
verbose_name_plural = 'Devices'
def __str__(self):
return self.model
class Country(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
Admin.py
from django.contrib import admin
from .models import Notification
admin.site.register(Notification)
Edit:
Thank you all the problem is solved
The problem was caused by some entries in device model that did have None in the model field so there was a problem displaying it correctly.
According to https://code.djangoproject.com/ticket/2169 :
When a class has a field that isn't shown in the admin interface but
must not be blank, it's impossible to add a new one. You get a cryptic
"Please correct the error below." message with no shown errors. The
error message should probably say something about a hidden field.
Now ManyToManyFields don't need null=True, try removing those statements and see if you get an improvement.
Also, try adding the Country and Device models in admin.py so admin can see them and display them.
https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#working-with-many-to-many-models
Define an inline for the many-to-manys in admin.py:
from django.contrib import admin
class DeviceInline(admin.TabularInline):
model = Notification.device.through
class CountryInline(admin.TabularInline):
model = Notification.country.through
class NotificationAdmin(admin.ModelAdmin):
inlines = [
DeviceInline, CountryInline
]
exclude = ("device", "country")
This my model of first Database DB1:
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=100, null=True)
address = models.TextField(max_length=200, null=True)
website = models.CharField(max_length=200, null=True)
conatct_no = models.CharField(max_length=20, null=True)
email = models.EmailField(max_length=20, null=True)
logo = models.FileField(upload_to='logo/', blank=True, null=True)
created = models.DateTimeField('company created', auto_now_add=True)
updated = models.DateTimeField('company updated', auto_now=True, null=True)
def __unicode__(self): # Python 3: def __str__(self):
return self.name
Model of 2nd Database Db2:
from django.db import models
from leavebuddymaster.models import Company
class Department(models.Model):
company = models.ForeignKey(Company)
department_name = models.CharField(max_length=50, null=True)
created = models.DateTimeField('department created', auto_now_add=True)
updated = models.DateTimeField('department updated', auto_now=True, null=True)
def __unicode__(self): # Python 3: def __str__(self):
return self.department_name
Now when i open the Department table it gives me a error as:
ProgrammingError at /admin/leavebuddyapp/department/
(1146, "Table 'leavebuddy_master.leavebuddyapp_department' doesn't exist")
I have done all the settings in settings.py correctly for the two databases. Can you please guide me in the right direction. Thanx in advance.
You're correct, Django does not currently support foreign key relationships spanning multiple databases.
From Cross-database relations [Edit 2020: Django version bump]:
If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.
This is because of referential integrity. In order to maintain a relationship between two objects, Django needs to know that the primary key of the related object is valid. If the primary key is stored on a separate database, it’s not possible to easily evaluate the validity of a primary key.
A solution I thought up that you could try (though it may present other problems):
from leavebuddymaster.models import Company
class Department(models.Model):
company_id = models.IntegerField()
#property
def company(self):
return Company.objects.get(pk=self.company_id)
This allows you to refer to Department.company like you normally would in your example. Setting it would just be a matter of Department.company_id = Company.pk. Hope it helps, or at least inspires a better solution!