So, I am actively trying to create categories with subcategories. My current app is listings, and the idea is to create a ManyToManyField inside my Listing models. Here is my code inside models.py.
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
name = models.CharField(max_length=150, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
class Blist(models.Model):
name = models.CharField('Business Name', max_length=250)
address = models.CharField('Address', max_length=300)
city = models.CharField('City', max_length=100)
zip_code = models.CharField('Zip Code', max_length=10)
phone_number = models.CharField('Phone Number', max_length=20)
web = models.URLField('Website')
def __str__(self):
return self.name
But when I go into the shell to add items into the category, I'm getting errors:
django.db.utils.ProgrammingError: column listings_category.name does not exist
LINE 1: SELECT "listings_category"."id", "listings_category"."name",...
Once finished, I ran makemigrations and migrate, but I realize it is not creating the tables in my database. I'm using Postgresql.
What am I doing wrong here?
Related
I ahve a user model called TbUser and I have integrated a mysql legacy database with django. After doing migrations I have the follwing tables. django_seesion, django_migrations, django_content_type, django_admin_log, auth_permission, auth_group_permissions, auth_group
When I log in to django admin page, and click on the TbUser then select a random user I am getting the following error.
Exception Value:
(1146, "Table 'db.tb_user_groups' doesn't exist")
Should this table be created when migrations are run?
Could it be that this table is the auth_group, and django is looking for this one using the wrong table name?
users.models
class TbUser(AbstractBaseUser, PermissionsMixin):
id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4)
username = models.CharField(
max_length=40, blank=True, null=True, unique=True, db_column='usname')
password = models.CharField(
max_length=255, blank=True, null=True, db_column='psword')
email = models.CharField(max_length=255, blank=True, null=True)
role = models.ForeignKey(TbRole, on_delete=models.CASCADE)
department = models.ForeignKey(
'app.TbDepartment', on_delete=models.CASCADE, null=True, blank=True)
is_superuser = models.BooleanField(
default=False, blank=True, null=True, db_column='default_super')
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = TbUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
managed = False
db_table = 'tb_user'
admin.py
from app.models import TbDepartment
from django.contrib import admin
from .models import TbCustomer, TbRole, TbUser, TbUserRole
admin.site.register(TbUser)
admin.site.register(TbRole)
admin.site.register(TbUserRole)
admin.site.register(TbDepartment)
admin.site.register(TbCustomer)
UPDATE:
I have created in mysql a table called tb_user_groups and when doing the same action the next error appears
Exception Value:
(1146, "Table 'db.tb_user_user_permissions' doesn't exist")
How do I generate these tables?
Why don't you just use AbstractUser. It has everything configured, and you can customize it if you want. In this case you shouldn't get tb_user_groups doesn't exist error.
class TbUser(AbstractUser):
REQUIRED_FIELDS = []
objects = TbUserManager()
I am trying to import data from an csv file into a django db using django-import-export. My problem is trying to upload data with a ForeignKey as an object. I have migrated, followed docs, and still no solution. You can see my error below in the django admin:
Here is my csv data with a blank 'Id' column:
models.py
from django.db import models
from django.shortcuts import reverse
from urllib.parse import urlparse
class States(models.Model):
name = models.CharField(max_length=96, blank=False, unique=True)
abbrv = models.CharField(max_length=2, null=True, blank=True)
class Meta:
ordering = ['name']
verbose_name = 'State'
verbose_name_plural = 'States'
def __str__(self):
return f'{self.name}'
class Person(models.Model):
last_name = models.CharField(
max_length=255, help_text="Enter your last name.")
first_name = models.CharField(
max_length=255, help_text="Enter your first name or first initial.")
address = models.CharField(
max_length=255, blank=True, help_text="Enter your street address.")
city = models.CharField(
max_length=255, blank=True, help_text="Enter your city.")
state = models.ForeignKey('States', to_field='name', on_delete=models.SET_NULL, null=True)
zipcode = models.CharField(max_length=50)
website = models.URLField(
max_length=255, blank=True)
profession = models.CharField(max_length=50, blank=True)
# META CLASS
class Meta:
verbose_name = 'Person'
verbose_name_plural = 'Persons'
ordering = ['last_name', 'first_name']
# TO STRING METHOD
def __str__(self):
"""String for representing the Model object."""
return f'{self.last_name}, {self.first_name}'
admin.py:
from django.contrib import admin
from .models import Person, States
from import_export.admin import ImportExportModelAdmin
from import_export.widgets import ForeignKeyWidget
from import_export import fields, resources
class PersonResource(resources.ModelResource):
state = fields.Field(
column_name='state',
attribute='state',
widget=ForeignKeyWidget(States, 'name'))
class Meta:
model = Person
class PersonAdmin(ImportExportModelAdmin):
list_display = ('last_name', 'first_name', 'state')
search_fields = ('first_name', 'last_name' )
resources_class = PersonResource
admin.site.register(Person, PersonAdmin)
admin.site.register(States)
I think you need to specify both in your question here, as well as to Django how you want the id field treated.
Do you want it propagated with the Django id or pk (sometimes the same sometimes not)? Then you would have id=self.id or id=self.pk somewhere in your view for the datatable.
Do you want your database to create a unique key?
You would need to add some functionality someplace to tell Django how to fill in that field.
Also, if you want it to create an id different from the Django id or pk then you would need to add the field to your model.
https://docs.djangoproject.com/en/3.1/ref/forms/validation/
https://docs.djangoproject.com/en/3.1/ref/validators/
https://docs.djangoproject.com/en/3.1/ref/forms/api/
Or, perhaps after Validation of the form, when you create the object. Add something to the effect of id=[database function to create unique id].
Another solution might be a templateTag or templateFilter to create a value on the form side if you want to create the id based on info contained in the form. Like combining last 4 of name with time of submission.
https://docs.djangoproject.com/en/3.1/ref/templates/builtins/
https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/
Having just re-read your question, also, I'm not sure but you might be asking if the database can support an embedded reference to another object. Is ID a reference to another model's key? That's a whole different question. And it is database specific.
Last Suggestion: Perhaps a re-read of:
https://docs.djangoproject.com/en/3.1/ref/forms/fields/#fields-which-handle-relationships
This error is occur because your id did not received an id or int value it received a str type of value Wyoming try to pass int value in id
Update
just update your PersonResource Meta class like this
class PersonResource(resources.ModelResource):
state = fields.Field(
column_name='state',
attribute='state',
widget=ForeignKeyWidget(States, 'name'))
class Meta:
model = Person
import_id_fields = ['id']
The default field for object identification is id, you can optionally
set which fields are used as the id when importing
check official doc. for more information.
I am trying to create a cart model using ForeignKey relation with User.
My mall/models.py:
from django.db import models
from django.contrib.auth.models import User
class products(models.Model):
image = models.ImageField(upload_to='products/', blank=True)
name = models.CharField(max_length=100)
detail = models.TextField(max_length=100, verbose_name='detail of product')
price = models.FloatField()
def __str__(self):
return self.name
class cart(models.Model):
item = models.OneToOneField(products, on_delete=models.CASCADE)
user = models.ForeignKey(User, null=True, blank=True, default=None, on_delete=models.CASCADE)
def __str__(self):
return self.item.name
I am getting a error like this:
django.db.utils.IntegrityError: NOT NULL constraint failed: new__mall_cart.user_id
whenever I am trying to migrate it. Its showing the same error if I am migrating the products class alone as well
.
I have provided null=True as well as blank=True and the superuser is created with the name of admin. What is issue here?
I'm working on an application in the saas model (django 2.1). I use the django tenants plugin (https://github.com/tomturner/django-tenants).
My problem is to display all tenants in the "public" schema. In such a way as to see how much each tenant has users, to be able to manage them, etc.
Is it a good architectural solution to put a foreign key into Tenant in the User model and save this column during the registration process?
Is there another way to do it?
Below is example, pseudo code:
class Tenant(TenantMixin):
name = models.CharField(_('Name of company'), max_length=50, unique=True)
on_trial = models.BooleanField(default=True)
paid_until = models.DateTimeField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
auto_create_schema = True
def __str__(self):
return self.name
def get_name(self):
return self.name
class Domain(DomainMixin):
pass
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('Email address'), unique=True)
first_name = models.CharField(_('First name'), max_length=60, blank=True)
last_name = models.CharField(_('Last name'), max_length=60, blank=True)
member_of_company = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name='users', null=True, blank=True)
You can iterate over your tenants and get the Users for each tenant with the following code:
from django.db import connection
from django.contrib.auth import get_user_model
from tenant_schemas.utils import get_tenant_model
UserModel = get_user_model()
TenantModel = get_tenant_model()
for tenant in TenantModel.objects.all():
connection.set_tenant(tenant)
tenant_users = UserModel.objects.all()
# Do whatever you want with your users
I have created a app using the following Model
models.py
class Vendor(models.Model):
name = models.CharField(max_length=100, unique=True, blank=False)
def __str__(self):
return self.name
class Model(models.Model):
name = models.CharField(max_length=100, unique=True, blank=False)
def __str__(self):
return self.name
class Request(models.Model):
job_reference = models.CharField(max_length=100, unique=True, blank=False)
def __str__(self):
return self.job_reference
class Device(models.Model):
Vendor = models.ForeignKey('Vendor')
Model = models.ForeignKey('Model')
device_id = models.CharField(max_length=255, unique=True, blank=True)
is_encrypted = models.BooleanField()
is_medical = models.BooleanField()
request_job_reference = models.ForeignKey('Request')
submitted = models.DateTimeField(default=timezone.now)
When i go to the admin page I can add new devices which displayed each of the fields and the "Vendor" and "Model" allows me to either select an existing entry or has a plus icon to add a new entry (which is great)
Django_Admin_form
When i create a form for my app
forms.py
from django import forms
from . models import Device
class AddDevice(forms.ModelForm):
class Meta:
model = Device
fields = ('Vendor', 'Model', 'device_id', 'is_encrypted', 'is_medical', 'submitted')
The form on my webpage display ok however there is no option to insert a new entry to "Vendor" or "Model".
Webpage Form
I have looked on other posts on here as users have had the same issue and it's been suggested to use "ModelChoiceField" but unfortunately it still doesn't make any sense to me. Either i'm completely missing something or I have setup my models in a way which is making things harder for myself.
Can anyone explain how I can go about doing this?