Django change_list editable fields header rows and items rows - django

I need to have multiple editable rows Header and Items of products and variants of products in Django Admin change_list.html / change_list_results.html like the image below:
Example result
this is my model:
class VariantProduct(models.Model):
product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE)
sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True,
help_text='SKU', unique=True)
ean_13 = models.BigIntegerField('EAN 13',
validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")],
blank=True, null=True, help_text='Codice numerico EAN 13')
ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True,
help_text='Codice alfanumerico 128')
qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255,
help_text="digitare il codice per la generazione del QR Code")
barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True)
quantity = models.IntegerField('Quantità', blank=True, null=True)
class Meta:
verbose_name = _('prodotto')
verbose_name_plural = _("prodotti")
ordering = ['name']
class VariantProduct(models.Model):
product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE)
sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True,
help_text='SKU', unique=True)
ean_13 = models.BigIntegerField('EAN 13',
validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")],
blank=True, null=True, help_text='Codice numerico EAN 13')
ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True,
help_text='Codice alfanumerico 128')
qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255,
help_text="digitare il codice per la generazione del QR Code")
barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True)
quantity = models.IntegerField('Quantità', blank=True, null=True)
qta_stock_add = models.PositiveSmallIntegerField('Q.ta +', help_text='Diminuisci N. Prodotti', blank=True,
null=True, )
qta_stock_sub = models.PositiveSmallIntegerField('Q.ta -', help_text='Diminuisci N. Prodotti', blank=True,
null=True, )
minimal_quantity = models.IntegerField('Scorta Minima', blank=True, null=True,
help_text='Scorta minima di magazzino, può essere negativa per gestione sotttottoscorta')
image = models.ImageField(upload_to='prodotti/%Y/%m/%d',
verbose_name=_('Immagine Variante'), blank=True, null=True)
state = models.BooleanField('Attivo', help_text='Stato della variante prodotto attivo/disattivo', default=True)
price = models.DecimalField(_('Prezzo'), max_digits=8, decimal_places=2, default=0.00)
dealer_price = models.DecimalField(_('Prezzo Rivenditore'), max_digits=8, decimal_places=2, default=0.00)
size = models.ForeignKey(Size, verbose_name=_('Taglia'), blank=True, null=True, on_delete=models.PROTECT)
color = models.ForeignKey(Color, verbose_name=_('colore'), blank=True, null=True, on_delete=models.PROTECT)
weight = models.DecimalField(_('Peso gr.'), blank=True, null=True, decimal_places=2, max_digits=10,
help_text=_('Peso in grammi'))
height = models.IntegerField(_('Altezza cm'), blank=True, null=True,
help_text=_('Altezza in grammi'))
width = models.IntegerField(_('Larghezza cm'), blank=True, null=True,
help_text=_('Larghezza in grammi'))
length = models.IntegerField(_('Lunghezza cm'), blank=True, null=True,
help_text=_('Lunghezza in grammi'))
class Meta:
verbose_name = _('Variante Prodotto')
verbose_name_plural = _('Varianti Prodotto')
def __str__(self):
return '{cod} - {name}'.format(cod=self.sku, name=self.product.name)
Is possible to show on django admin page the row of a product an relative rows of variants and make editable the fields of "quantity" on all rows?
Thanks in advance.
W.

Related

How to get difference between two annotate fields in django orm

The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct.
In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account
queryset = PersonalAccount.objects.select_related(
'apartment', 'apartment__house', 'apartment__section', 'apartment__owner',
).annotate(
balance=
Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0))
-
Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0))
).order_by('-id')
class PersonalAccount(models.Model):
objects = None
class AccountStatus(models.TextChoices):
ACTIVE = 'active', _("Активен")
INACTIVE = 'inactive', _("Неактивен")
number = models.CharField(max_length=11, unique=True)
status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE)
apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL,
related_name='account_apartment')
class CashBox(models.Model):
objects = None
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
type = models.BooleanField(default=True)
sum = models.DecimalField(max_digits=10, decimal_places=2)
comment = models.TextField(blank=True)
payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL)
owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner')
manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager')
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.SET_NULL, related_name='cash_account')
receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL)
class Receipt(models.Model):
objects = None
class PayStatus(models.TextChoices):
PAID = 'paid', _("Оплачена")
PARTIALLY_PAID = 'partially_paid', _("Частично оплачена")
NOT_PAID = 'not_paid', _("Не оплачена")
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
date_start = models.DateField(default=datetime.date.today)
date_end = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
status_pay = models.CharField(max_length=15, choices=PayStatus.choices, default=PayStatus.NOT_PAID)
sum = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, blank=True)
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.CASCADE, related_name='receipt_account')
tariff = models.ForeignKey('Tariff', null=True, on_delete=models.CASCADE)
apartment = models.ForeignKey('Apartment', null=True, on_delete=models.CASCADE,
related_name='receipt_apartment')

how to call filter database with "Id " Django,

I want to make pay form, but I cannot show produk in orederitem, please helping me to show orderitem :v. I am really newbie in here .
models.py
class Order(models.Model):
name = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
order_data = models.DateTimeField(auto_now_add=True)
selesai = models.BooleanField(default=False, blank=True, null=True)
status = models.BooleanField(default=False, blank=True, null=True)
id_transaksi = models.CharField(max_length=200, null=True)
bukti = models.ImageField(null=True, blank=True)
ongkir = models.CharField(max_length=200, null=True)
total = models.CharField(max_length=200, null=True)
total_harga = models.CharField(max_length=200, null=True)
pembayaran = models.CharField(max_length=200, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0)
date_added = models.DateTimeField(auto_now_add=True)
views.py
def pembayaran(request):
customer = request.user.profile
ido = Order.objects.filter(id)
orders = Order.objects.filter(name=customer, selesai=True)
pengiriman = Pengiriman.objects.filter(name=customer)
OrderItems = OrderItem.objects.filter(order=ido)
print(OrderItems)
context = {'orders': orders,'pengiriman' :pengiriman , 'OrderItems': OrderItems }
return render(request, 'store/pembayaran.html', context)

How to use django-filter to make a filter with reverse foreign key value?

I have a models
class TDebtor(models.Model):
first_name = models.CharField(max_length=250, blank=True, null=True)
surname = models.CharField(max_length=250, blank=True, null=True)
middle_name = models.CharField(max_length=250, blank=True, null=True)
iin = models.CharField(max_length=50, blank=True, null=True)
alive = models.BooleanField(blank=True, null=True)
birth_date = models.DateField(blank=True, null=True)
class TDebtData(models.Model):
agr_num = models.CharField(max_length=250, blank=True, null=True)
id_num = models.CharField(max_length=250, blank=True, null=True)
loan_amount = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
principal_amount = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
id_debtor = models.ForeignKey('TDebtor', models.DO_NOTHING, related_name="debtor_debt_data")
views.py
class ProductList(ListAPIView):
queryset = TDebtor.objects.prefetch_related(Prefetch('debtor_debt_data', queryset=TDebtData.objects.select_related('id_debtor')))
for i in queryset:
print(i.debtor_debt_data.agr_num)
serializer_class = TDebtorSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['iin', 'first_name', 'surname', 'middle_name', 'birth_date',
'alive']
if I'll make a filter with the fields of TDebtor it's okay, but how I can filter with agr_num?, I mean if I'll send agr_num=1238HFD32 it will return me TDebtor that has this agr_num
Use RELATED_NAME__FIELD. In your case debtor_debt_data__agr_num
class ProductList(ListAPIView):
...
filterset_fields = [..., `debtor_debt_data__agr_num`]
Docs in https://django-filter.readthedocs.io/en/stable/index.html

How to access related values with select_related()

I have a QuerySet that I'm attempting to work with the values on related tables. I see the related tables/values when I run the queryset.query, however I'm not sure how to pull those values for use in forms/tables.
Here is my QuerySet Object:
tpList = AppCustomerTpRel.objects.filter(idcst_rel=selection).select_related('idcst_rel', 'idtrp_rel').values()
Here are the related Models.
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='idtrp_rel')
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)
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 AppCustomerCst(models.Model):
id_cst = models.AutoField(primary_key=True)
is_active_cst = models.BooleanField()
name_cst = models.CharField(max_length=50, blank=True, null=True)
address_1_cst = models.CharField(max_length=50, blank=True, null=True)
address_2_cst = models.CharField(max_length=50, blank=True, null=True)
address_3_cst = models.CharField(max_length=50, blank=True, null=True)
city_cst = models.CharField(max_length=50, blank=True, null=True)
state_cst = models.CharField(max_length=50, blank=True, null=True)
zip_cst = models.CharField(max_length=10, blank=True, null=True)
country_cst = models.CharField(max_length=50, blank=True, null=True)
salesrep_cst = models.CharField(max_length=50, blank=True, null=True)
type_cst = models.CharField(max_length=10, blank=True, null=True)
is_allowed_flat_cst = models.BooleanField()
iddef_cst = models.IntegerField()
date_created_cst = models.DateTimeField()
date_suspended_cst = models.DateTimeField(blank=True, null=True)
date_first_tran_cst = models.DateTimeField(blank=True, null=True)
date_last_tran_cst = models.DateTimeField(blank=True, null=True)
is_credit_hold_cst = models.BooleanField()
old_balance_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_notify_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_statement_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_conversion_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_cst = models.DecimalField(max_digits=8, decimal_places=2)
receive_emails_cst = models.BooleanField()
contact_domain_cst = models.CharField(max_length=100, blank=True, null=True)
I am trying to work with values from the 'AppCustomerTpRel' Table.
I have tried app_customer_tp_rel.id_rel as well as app_customer_tp_rel__id_rel with the SQL Table Names, I have also tried both using the Model Name AppCustomerTpRel
TIA!
Just wright all related fields the you need in values()
tpList = AppCustomerTpRel.objects.filter(
idcst_rel=selection
).select_related(
'idcst_rel',
'idtrp_rel'
).values(
'idtrp_rel__id_trp',
'idtrp_rel__tpid_trp',
'idtrp_rel__name_trp',
...
)

Django foreignkey field filtering problem

I´m trying to filter a queryset with a ForeignKey field but I get the following error:
Cannot resolve keyword 'workflowcontenidos' into field. Choices are:
categoria_producto, descripcion_brief, descripcion_long, estatus_contenido,
estatus_contenido_id, foto_1, foto_2, id, perfil_cliente, productosbase, usos,
video
My models are:
class WorkflowContenidos(models.Model):
estatus = models.CharField(max_length=200, help_text="Estatus de contenido", blank=False, null=True)
def __str__(self):
return str(self.estatus)
class Categorias_Producto(models.Model):
categoria_producto = models.CharField(max_length=50, help_text="Catergoría de producto", unique=True, blank=False, null=True)
descripcion_brief = models.TextField(max_length=200, help_text="Descripción resumida", blank=True, null=True)
descripcion_long = models.TextField(max_length=500, help_text="Descripción extendida", blank=True)
usos = models.CharField(max_length=200, help_text="Usos (separados por comas)", blank=True, null=True)
foto_2 = models.ImageField(upload_to='', default="", blank=False, null=False)
foto_1 = models.ImageField(upload_to='', default="", blank=False, null=False)
video = models.URLField("Link brand video", max_length=128, blank=True, null=True)
perfil_cliente = models.CharField(max_length=200, help_text="Perfil de cliente", blank=True, null=True)
estatus_contenido = models.ForeignKey("WorkflowContenidos", help_text="Estatus del contenido", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return str(self.categoria_producto)
The "estatus" values in the WorkflowContenidos model are:
Incompleto
Revisión
Aprobado
The view:
def WorkflowContenidosView(request):
lista_visualizacion = Categorias_Producto.objects.filter(workflowcontenidos__estatus='Incompleto')
return render(request, 'catalog/content-workflow.html', {
'lista_visualizacion': lista_visualizacion
})
lista_visualizacion = Categorias_Producto.objects.filter(estatus_contenido__estatus='Incompleto')