I have an Orders model, in which I didn't have slug field before. So I decided to add a slug field to it. But when I run makemigrations command it says 'No changes detected'. I've tried to manually create migration and run it, but it didn't affect my database.
Yes, I did check in settings, app is registered there.
Model:
class Orders(models.Model):
customer = models.ForeignKey('contractors.Customers',
models.DO_NOTHING, blank=True, null=True)
slug = models.SlugField(max_length=150, blank=True)
employee = models.ForeignKey('employees.Employees',
models.DO_NOTHING, blank=True, null=True)
order_date = models.DateField(blank=True, null=True, auto_now=True)
required_date = models.DateField(blank=True, null=True)
shipped_date = models.DateField(blank=True, null=True)
ship_via = models.ForeignKey('contractors.Shippers',
models.DO_NOTHING, db_column='ship_via',
blank=True, null=True)
freight = models.FloatField(blank=True, null=True)
ship_name = models.CharField(max_length=40, blank=True, null=True)
ship_address = models.CharField(max_length=60, blank=True, null=True)
ship_city = models.CharField(max_length=15, blank=True, null=True)
ship_region = models.CharField(max_length=15, blank=True, null=True)
ship_postal_code = models.CharField(max_length=10, blank=True, null=True)
ship_country = models.CharField(max_length=15, blank=True, null=True)
class Meta:
managed = False
db_table = 'orders'
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.customer + "-" + str(self.order_date))
super(Orders, self).save(*args, **kwargs)
def get_absolute_url(self):
return u'/orders/%d' % self.pk
def __str__(self):
return f"{self.customer} {self.order_date}"
My attempt to manually create migration:
# Generated by Django 3.2.7 on 2021-11-10 13:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0008_alter_orderdetails_options'),
]
operations = [
migrations.AddField(
model_name='orders',
name='slug',
field=models.SlugField(max_length=150, blank=True),
preserve_default=False,
),
]
You have set managed = False in your model Meta. Django will not manage the model for you, see here. Set it to True if you want Django to manage migrations for you.
problem
class Meta:
managed = False
db_table = 'orders'
solution
class Meta:
db_table = 'orders'
Related
I am trying to filter my many to many variation fields with respect to the product. means, I only want the variations related to the current product to show in the admin page. now its showing all the variations available for every product.
I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations?
most of the questions in stack overflow Is based on the current user, which is easy to get? but how should I get the specific product(id) that is opened in the admin panel.
admin.py
from django.contrib import admin
from .models import *
from products.models import Variation
class CartAdmin(admin.ModelAdmin):
list_display = ('cart_id', 'date_created')
class CartItemAdmin(admin.ModelAdmin):
list_display = ('user','cart', 'product', 'quantity','is_active')
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "variation":
product = Products.objects.get(id='??') # how I get the current product in the cart or order
kwargs["queryset"] = Variation.objects.filter(product=product.id)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Cart, CartAdmin)
admin.site.register(CartItem, CartItemAdmin)
CartItem Model
class CartItem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation = models.ManyToManyField(Variation, blank=True)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
def item_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product.name
Product and Variation Model
class Products(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='name', max_length=100, unique=True)
isbn = models.CharField(max_length=20, unique=True, blank=True, null=True)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True)
author = models.CharField(max_length=100)
Publisher = models.CharField(max_length=100, blank=True, default=None)
release_date = models.DateField(blank=True, null=True, default=None)
price = models.IntegerField(default=None)
stock = models.IntegerField(default=None)
is_available = models.BooleanField(default=True)
cover_image = models.ImageField(upload_to='images/products')
image1 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image2 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image3 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
description = models.TextField(max_length=2000, blank=True, default=None)
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
number_of_pages = models.IntegerField(blank=True, null=True)
weight = models.IntegerField(blank=True, null=True)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
spine_width = models.IntegerField(blank=True, null=True)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def get_url(self):
return reverse('product-view', args=[self.slug])
def __str__(self):
return self.name
class Variation(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation_category = models.CharField(max_length=100, choices=variation_category_choice)
variation_value = models.CharField(max_length=100, choices=variation_value_choice)
is_available = models.BooleanField(default=True)
date_added = models.DateTimeField(auto_now_add=True)
objects = VariationManager()
def __str__(self):
return self.variation_value
I am getting an error in admin console while trying to open a model . How to fix it
Model.py
class TbSysEmailconfig(models.Model):
id = models.ForeignKey('self', models.DO_NOTHING, db_column='Id', primary_key=True) # Field name made lowercase.
emailtemplateid = models.ForeignKey(TbMasEmailtemplate, models.DO_NOTHING, db_column='EmailTemplateId')
emailfromname = models.CharField(db_column='EmailFromName', max_length=100, blank=True, null=True)
emailfrom = models.CharField(db_column='EmailFrom', max_length=100)
credential = models.CharField(db_column='Credential', max_length=100)
password = models.CharField(db_column='Password', max_length=100)
post = models.IntegerField(db_column='Post', blank=True, null=True)
host = models.CharField(db_column='Host', max_length=100)
priority = models.CharField(db_column='Priority', max_length=100, blank=True, null=True)
maximumday = models.IntegerField(db_column='MaximumDay', blank=True, null=True)
maximumminute = models.IntegerField(db_column='MaximumMinute', blank=True, null=True)
systemid = models.IntegerField(db_column='SystemId')
partfiletemplate = models.CharField(db_column='PartFileTemplate', max_length=500, blank=True, null=True)
comment = models.CharField(db_column='Comment', max_length=1000, blank=True, null=True)
ismaildefault = models.SmallIntegerField(db_column='IsMailDefault')
maildefault = models.CharField(db_column='MailDefault', max_length=4000, blank=True, null=True)
createddate = models.DateTimeField(db_column='CreatedDate')
createdbyuserid = models.IntegerField(db_column='CreatedByUserId')
updateddate = models.DateTimeField(db_column='UpdatedDate')
updatedbyuserid = models.IntegerField(db_column='UpdatedByUserId')
delflag = models.SmallIntegerField(db_column='DelFlag')
class Meta:
db_table = 'TB_SYS_EmailConfig'
admin.py
from django.contrib import admin
from .model import TbSysEmailconfig
#Modifire
admin.site.register(TbSysEmailconfig)
When I select some item
it show this error
Remove the id field from your model, as you have referenced it as a foreign key to the model itself. The id field is automatically generated if no field in the model is explicitly chosen.
I have the following 2 models that I want to use in a form set. I'm not sure what I've got wrong
models.py
class AppTradingPartnerTrp(models.Model):
id_trp = models.AutoField(primary_key=True)
tpid_trp = models.CharField(max_length=50, blank=True, null=True)
name_trp = models.CharField(max_length=50)
description_trp = models.CharField(max_length=100, blank=True, null=True)
idtrn_trp = models.ForeignKey('AppTransmissionTrn', models.DO_NOTHING, db_column='idtrn_trp', blank=True, null=True)
class AppCustomerTpRel(models.Model):
id_rel = models.AutoField(primary_key=True)
idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel')
idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='id_trp')
cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True)
sender_id_rel = models.CharField(max_length=50, blank=True, null=True)
old_vendor_rel = models.CharField(max_length=50, blank=True, null=True)
vendor_name_rel = models.CharField(max_length=50, blank=True, null=True)
category_rel = models.CharField(max_length=50, blank=True, null=True)
And here is where I'm trying to create the formset:
forms.py
CstVendorNoFormSet = inlineformset_factory(AppCustomerTpRel, AppTradingPartnerTrp, exclude=())
However when I do runserver I'm getting:
ValueError: 'AppTradingPartnerTrp' has no ForeignKey to 'AppCustomerTpRel'.
It looks like you've got your ForeignKey relationships the wrong way round.
Side note: I noticed that in your 'AppTradingPartnerTrp' model, for the idtrn_trp FK field, you have got 'AppTransmissionTrn' as a string, I think it should be AppTransmissionTrn without the apostrophes.
You have reversed the model order
inlineformset_factory(parent_model, model, ... )
Parent model is AppTradingPartnerTrp as it has multiple AppCustomerTpRel (foreign key) so
CstVendorNoFormSet = inlineformset_factory(AppTradingPartnerTrp, AppCustomerTpRel, exclude=())
My group and I are attempting to rewrite our website. We are keeping an Oracle database back-end, and rewriting the front-end with Python Django.
No problem connecting to Oracle, or accessing the datatables. Now I'm trying to add an Oracle view to the models.py, and I can't get it to work.
I googled this question with many results, so I know it is possible and apparently common, but I can't get it to work.
All I've done so far is add the class to models.py. We are using PhCharm as our IDE.
When I try to access the data using the Python Console, I can import the class, but when I try to load the QuerySet I get the error "Unable to get repr for " in the result window.
Does anyone see something I'm missing from my model?
Here is the model:
class LawBillRoleActionInfoView(LawBaseClass):
combo_id = models.AutoField(primary_key=True)
rltp_role_cd = models.CharField(max_length=2, blank=True)
bill_dft_no = models.CharField(max_length=6, blank=True)
session_id = models.IntegerField(blank=True, null=True)
ebrl_appl_seq = models.IntegerField(blank=True, null=True)
enty_id_seq = models.IntegerField(blank=True, null=True)
lst_nm = models.CharField(max_length=100, blank=True)
fst_nm = models.CharField(max_length=40, blank=True)
mi = models.CharField(max_length=1, blank=True)
entity = models.CharField(max_length=145, blank=True, null=True)
prtydist = models.CharField(max_length=11, blank=True, null=True)
blac_appl_seq = models.IntegerField(blank=None, null=True)
role_descr = models.CharField(max_length=80, blank=True)
shr_ttl = models.CharField(max_length=80, blank=True)
lmt_ind = models.CharField(max_length=1, blank=True)
bltp_bill_typ_cd = models.CharField(max_length=2, blank=True)
bill_no = models.IntegerField(blank=True, null=True)
actn_descr = models.CharField(max_length=80, blank=True)
actn_dt = models.DateField(blank=True, null=True)
sess_law_chpt_no = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'law_bill_role_action_info_vw'
unique_together = (('bill_dft_no', 'rltp_role_cd', 'session_id'),)
app_label = 'laws'
Here are the commands I am running from the Python Console:
from laws.models import LawBillRoleActionInfoView
bill_qs = LawBillRoleActionInfoView.objects.all()
Here is the LawBaseClass:
Base Class
class LawBaseClass(models.Model):
"""
Base class
"""
created_by = models.CharField(max_length=30, blank=True, null=True)
dtm_created = models.DateField(blank=True, null=True)
mod_by = models.CharField(max_length=30, blank=True, null=True)
dtm_mod = models.DateField(blank=True, null=True)
class Meta:
managed = False
abstract = True
I have the following models.py
class Institution(models.Model):
name = models.CharField(_('Name'), max_length=150, db_index=True)
slug = models.SlugField(_('Domain name'), unique=True)
class Company(Institution):
type = models.PositiveSmallIntegerField()
class HC(Institution):
type = models.PositiveSmallIntegerField()
bed_count = models.CharField(max_length=5, blank=True, null=True)
I have the models that are generated from Institutions and I want to follow the Institutions from the Profile model.
class Profile(models.Model):
user = models.OneToOneField(User)
about = models.TextField(_('About'), blank=True, null=True)
following_profile = models.ManyToManyField('self', blank=True, null=True)
following_institution = models.ManyToManyField(Institution, blank=True, null=True)
following_tag = models.ManyToManyField(Tag, blank=True, null=True)
I want to make M2M relations to all models that inherits Institutions. Is there a way to do this with Generic Relations?
Sounds like you're ready for polymorphism:
https://django-polymorphic.readthedocs.org
Otherwise you'll have to add them individually, so your Institution model would look something like this:
class Institution(models.Model):
name = models.CharField(_('Name'), max_length=150, db_index=True)
slug = models.SlugField(_('Domain name'), unique=True)
class Meta:
abstract = True
and the manytomany just basic like this:
following_company = models.ManyToManyField(Company, blank=True, null=True)
following_hc = models.ManyToManyField(Institution, blank=True, null=True)