Django smart selects is not working properly - python-3.x

I try to chain four categories with django smart select but it does not work properly. Django does not take or input values from in the last one. clothing_size. It is working properly till clothing sizes. That selectbox is always empty. My model:
What could be the problem here? That does not seem like js problem, because other fields are working properly.
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
# Create your models here.
class MainCategory(models.Model):
name = models.CharField(max_length=20, null=True)
def __str__(self):
return self.name
class ClothingType(models.Model):
main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True)
clothing_type = models.CharField(max_length=64, null=True)
def __str__(self):
template = '{0.main_category} {0.clothing_type}'
return template.format(self)
class ClothingSubType(models.Model):
main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True)
# clothing_type = models.ForeignKey(ClothingType, on_delete=models.CASCADE, null=True)
clothing_type = ChainedForeignKey(ClothingType, chained_field="main_category", chained_model_field="main_category", show_all=False, auto_choose=True, sort=True, null=True)
clothing_sub_type = models.CharField(max_length=254, null=True)
def __str__(self):
template = '{0.main_category} {0.clothing_type} {0.clothing_sub_type}'
return template.format(self)
class ClothingSize(models.Model):
main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True)
clothing_type = ChainedForeignKey(ClothingType, chained_field="main_category", chained_model_field="main_category", show_all=False, auto_choose=True, sort=True, null=True)
clothing_sub_type = ChainedForeignKey(ClothingSubType, chained_field="clothing_type", chained_model_field="clothing_type", show_all=False, auto_choose=True, sort=True, null=True)
# clothing_sub_type = models.ForeignKey(ClothingSubType, on_delete=models.CASCADE, null=True)
clothing_size = models.CharField(max_length=30, null=True)
def __str__(self):
template = '{0.main_category} {0.clothing_type} {0.clothing_sub_type} {0.clothing_size}'
return template.format(self)
class Product(models.Model):
name = models.CharField(max_length=30, null=True)
sku = models.CharField(max_length=20, null=True)
main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True)
clothing_type = ChainedForeignKey(
ClothingType,
chained_field="main_category",
chained_model_field="main_category",
show_all=False,
auto_choose=True,
sort=True,
null=True
)
product_category = ChainedForeignKey(
ClothingSubType,
chained_field="clothing_type",
chained_model_field="clothing_type",
show_all=False,
auto_choose=True,
sort=True,
null=True
)
clothing_size = ChainedForeignKey(
ClothingSize,
chained_field="clothing_sub_type",
chained_model_field="clothing_sub_type",
show_all=False,
auto_choose=True,
sort=True,
null=True
)
def __str__(self):
template = '{0.name}'
return template.format(self)

Related

Django Models: Filter a subset of a query set

I have these two models:
class InspectionPoint(models.Model):
...
review_check = models.BooleanField(default = 0)
flight = models.ForeignKey(
Flight,
related_name='inspection_points',
on_delete=models.CASCADE,
null=True, blank=True
)
...
class ImageSnapshot(models.Model):
...
inspection = models.ForeignKey(
InspectionPoint,
on_delete=models.CASCADE,
related_name = 'snapshots'
)
flight = models.ForeignKey(
Flight,
related_name='snapshots',
on_delete=models.CASCADE,
null=True, blank=True
)
...
I already have snapshots queryset with:
snapshots = ImageSnapshots.objects.filter(flight=flight)
but that gives me all snapshots.
I want to filter snapshots that have only (review_check = True)
Any idea?
Try this:
ImageSnapshot.objects.filter(flight=flight, inspection__review_check=True)

Integrating a payment application (API) in a django application

I have a Django web application in which I would like to integrate a local payment API in order to enable customers who want to use their money from this payment application to pay their car insurance but honestly, I don't have any idea of how to do it.
Below are the related models (Contrat and Reglement):
class Contrat(models.Model):
Statut_contrat = (
('Encours', 'Encours'),
('Suspendu', 'Suspendu'),
('Expiré', 'Expiré'),
)
categorie_choices =(
('Tourisme', 'Tourisme'),
('Transport', 'Transport')
)
# numero_de_contrat = shortuuid.uuid()
type_contrat = models.ForeignKey(TypeContrat, on_delete=models.CASCADE, null=True, blank=False)
tca = models.DecimalField(_('TCA 4%'),max_digits=10, decimal_places=2, default=0.00)
numero_de_contrat = models.CharField(max_length=50, blank=True, null=True,db_index=True, unique=True)
statut_assurance =models.CharField(max_length=15, choices=Statut_contrat, default='Non')
vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE)
utilisateur = models.ForeignKey(User, on_delete=models.CASCADE)
nombre_de_mois = models.IntegerField(null=True, blank=True)
sous_couvert = models.CharField(_('S/C'),max_length=200, null=True, blank=True)
categorie = models.CharField(max_length=50, choices=categorie_choices, null=False, blank=False, default='Tourisme')
created = models.DateField(auto_now_add=True)
modified = models.DateField(auto_now=True)
active = models.BooleanField(default=True)
remainingdays=models.IntegerField(default=0)
blocked_date=models.DateField()
unblocked_date = models.DateField(null=True, blank=True)
history = HistoricalRecords()
class Meta:
ordering=('-created',)
#property
def static_id(self):
'C{0:07d}'.format(self.pk)
def __str__(self):
return str(self.numero_de_contrat)
def save(self, *args, **kwargs):
self.tca=self.type_contrat.montant_du_contrat*Decimal(0.04)
if self.statut_assurance=="Suspendu":
dt=abs(self.blocked_date-self.modified)
print('Difference est:',dt)
numberOfDaysLeft= self.remainingdays-dt.days
print('Big diff',numberOfDaysLeft)
self.remainingdays=numberOfDaysLeft
self.blocked_date=date.today()
super(Contrat, self).save(*args, **kwargs)
def activeStatus(self):
if self.nombre_de_mois==0:
return self.active==False
else:
return self.active==True
def get_NbDays(self):
if self.statut_assurance=='Encours':
# nb_Days = timedelta(days=self.remainingdays)+date.today()
nb_Days = timedelta(days=self.remainingdays)+self.blocked_date
print('Date de fin', nb_Days)
return nb_Days
elif self.statut_assurance=='Suspendu':
nb_Days = timedelta(days=self.remainingdays) + self.blocked_date
return nb_Days
else:
nb_Days = self.modified
return nb_Days
class Reglement(models.Model):
payment_list = (('Espece', 'Espece'),
('Cheque', 'Cheque'),
('Carte de crédit', 'Carte de crédit'),
('Carte de débit', 'Carte de débit'),
('A crédit', 'A crédit'),)
code_reglement = models.CharField(max_length=50, blank=True, null=True, db_index=True, unique=True)
contrat = models.ForeignKey(Contrat, on_delete=models.CASCADE)
utilisateur = models.ForeignKey(User, on_delete=models.CASCADE)
date_reglement = models.DateField(auto_now_add=True)
montant_a_regler = models.DecimalField(max_digits=10, decimal_places=2)
mode_de_paiment = models.CharField(max_length=15,choices=payment_list)
created = models.DateField(auto_now_add=True)
modified = models.DateField(auto_now=True)
regle = models.BooleanField(default=False)
history = HistoricalRecords()
class Meta:
ordering=('-created',)
#property
def static_id(self):
'R{0:07d}'.format(self.pk)
Please assist me

Django rest framework: how can I serialize multiple table to get combine JSON output

I am very new to django, any help highly appreciated. thanks in advance!
Here is my code 'model.py'
class Stocks(models.Model):
ticker = models.CharField(max_length=30, primary_key=True, unique=True)
company_name = models.CharField(max_length=100, blank=True, null=True)
sector = models.CharField(max_length=50, blank=True, null=True)
class Meta:
db_table = 'stocks'
def __str__(self):
return "%s %s %s" % (self.ticker, self.company_name, self.sector)
class QuarterlyFinance(models.Model):
ticker = models.ForeignKey(Stocks, db_column='ticker',on_delete=models.CASCADE,
related_name='quarter_result', blank=True, null=True)
quarter_end = models.DateTimeField(blank=True, null=True)
total_revenue = models.FloatField(blank=True, null=True)
net_income = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'quarterly_finance'
unique_together = (('ticker', 'quarter_end'),)
def __str__(self):
return "%s %s %s %s" % (self.ticker, self.quarter_end, self.total_revenue,
self.net_income)
serialize.py
class StocksSerialize(serializers.ModelSerializer):
class Meta:
model=Stocks
fields="__all__"
depth=1
class QuarterlyFinanceSerialize(serializers.ModelSerializer):
class Meta:
model=QuarterlyFinance
fields=['quarter_end', 'total_revenue','net_income']
depth=1
view.py
class DataClassView(APIView):
def get(self, request, format=None):
max_day = Advice.objects.latest('advice_date').advice_date
max_day=max_day.strftime("%Y-%m-%d")
qfinance = QuarterlyFinance.objects.filter(ticker='TCS')
stk = Stocks.objects.filter(ticker='TCS')
qfin_ser_obj = QuarterlyFinanceSerialize(qfinance, many=True)
stock_ser_obj = StocksSerialize(stk, many=True)
result = stock_ser_obj.data +qfin_ser_obj.data
return Response(result)
I want to return JSON output like this:
{
"ticker": "TCS",
"company_name": "Tata Consultancy Services Ltd",
"sector": "IT",
"qtr_result": [
{
"quarter_end": "2021-06-30T04:00:00",
"total_revenue": 454110000000,
"net_income": 90080000000
},
{
"quarter_end": "2021-03-31T04:00:00",
"total_revenue": 437050000000,
"net_income": 92460000000
},
{
"quarter_end": "2020-12-31T05:00:00",
"total_revenue": 420150000000,
"net_income": 87010000000
},
{
"quarter_end": "2020-09-30T04:00:00",
"total_revenue": 401350000000,
"net_income": 74750000000
}
]
}
my code is working but I am getting data from both table in separate array within JSON. I want QuarterlyFinance data should be inside Stock table data as an array.
class StocksSerialize(serializers.ModelSerializer):
quarter_result = QuarterlyFinanceSerialize(read_only=True, many=True)
class Meta:
model=Stocks
fields="__all__"
depth=1

I am trying to create drop down menu in django but my code is showing only text box ? Help Appricated

I have defined modles.py, view.py, and forms.py but unable to get the drop-down menu. at initial, I have created moodle.py using os_choice and later on a substitute in the operating_system. further, I have created forms and I am using crispy forms to render in front page. likewise, I have defined this in views.py but when I see it on the font page it shows only a text file, not a drop-down with choices.
Here is my model.py code:
from django.db import models
from django.utils.encoding import smart_text
from multiselectfield import MultiSelectField
# Create your models here.
class ResultQuery(models.Model):
os_choice = (
('Windows 10', 'Windows 10'),
('Windows 8', 'Windows 8'),
('Linux', 'Linux'),
)
operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice)
level = models.CharField(max_length=30)
program = models.CharField(max_length=30)
semester = models.CharField(max_length=20)
exam_year = models.IntegerField()
institute = models.CharField(max_length=4)
reg_no = models.CharField(max_length=50)
symbol_num = models.IntegerField()
student_name = models.CharField(max_length=50)
dob = models.DateField()
sgpa = models.TextField()
result = models.CharField(max_length=40)
name = models.CharField(max_length=30)
subject1_code=models.CharField(max_length=40)
subject1_title=models.CharField(max_length=40)
subject1_credit_hour=models.TextField()
subject1_grade_point=models.TextField()
subject1_grade=models.TextField()
subject1_remarks=models.CharField(max_length=20, null=True, blank=True)
subject2_code = models.CharField(max_length=40)
subject2_title = models.CharField(max_length=40)
subject2_credit_hour = models.TextField()
subject2_grade_point = models.TextField()
subject2_grade = models.TextField()
subject2_remarks = models.CharField(max_length=20, null=True, blank=True)
subject3_code = models.CharField(max_length=40)
subject3_title = models.CharField(max_length=40)
subject3_credit_hour = models.TextField()
subject3_grade_point = models.TextField()
subject3_grade = models.TextField()
subject3_remarks = models.CharField(max_length=20, null=True, blank=True)
subject4_code = models.CharField(max_length=40)
subject4_title = models.CharField(max_length=40)
subject4_credit_hour = models.TextField()
subject4_grade_point = models.TextField()
subject4_grade = models.TextField()
subject4_remarks = models.CharField(max_length=20, null=True, blank=True)
subject5_code = models.CharField(max_length=40)
subject5_title = models.CharField(max_length=40)
subject5_credit_hour = models.TextField()
subject5_grade_point = models.TextField()
subject5_grade = models.TextField()
subject5_remarks = models.CharField(max_length=20, null=True, blank=True)
subject6_code = models.CharField(max_length=40)
subject6_title = models.CharField(max_length=40)
subject6_credit_hour = models.TextField()
subject6_grade_point = models.TextField()
subject6_grade = models.TextField()
subject6_remarks = models.CharField(max_length=20, null=True, blank=True)
def __str__(self):
return smart_text(self.name)
Here is my forms.py
from django import forms
from search.models import ResultQuery
from django.forms import MultipleChoiceField, ChoiceField, Form
class ResultForm(forms.Form):
Reg_No=forms.CharField(label="Registration Number")
Name=forms.CharField(label="Your Name")
OS=forms.CharField(label="Operating System")
And here is my views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .forms import ResultForm
from .models import ResultQuery
def home(request):
form=ResultForm(request.POST or None)
template_name = "home.html"
context = {"form": form}
if form.is_valid():
objects = ResultQuery.objects.filter(reg_no=form.cleaned_data['Reg_No'], name=form.cleaned_data['Name'], operating_system=form.cleaned_data['OS'])
context['objects'] = objects
return render(request, template_name, context)
Have you tried doing it like so?
from django import forms
from search.models import ResultQuery
from django.forms import MultipleChoiceField, ChoiceField, Form
class ResultForm(forms.Form):
Reg_No=forms.CharField(label="Registration Number")
Name=forms.CharField(label="Your Name")
OS=forms.ChoiceField(choices=ResultQuery.os_choice)

strftime model object and display in html template

Good day, I want to strftime the created model instance and display it in the HTML template(as a transaction_id). But I don't seem to get it right. Thanks for your help.
models.py
class Order(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
phone_number = models.CharField(max_length=20)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
braintree_id = models.CharField(max_length=150, blank=True)
coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL)
discount = models.IntegerField(default=0, validators=[
MinValueValidator(0),
MaxValueValidator(100)
])
views.py
def order_list(request):#datetime.now().strftime("%Y%m%d%H%M%S")
transaction_id = Order.objects.get(created)
orders = Order.objects.all()
current_user = request.user
success = Order.objects.filter(user=current_user.id).filter(paid=True)
fail = Order.objects.filter(user=current_user.id).filter(paid=False)
return render(request, 'orders/order/order_list.html', {
'success': success,
'fail': fail,
'current_user': current_user,
'orders':orders,
'transaction_id':transaction_id,
})
html
<p class="card-text">
<mark style="color: whitesmoke; background-color: brown;border-radius: 3px;font-weight: bold;">{{transaction_id}}</mark>
</p>
you getting error of "transaction_id = Order.objects.get(created)" line
what is "created" in get() method
Well, this is what I did to fix this
I added the strftime func in my models.py
models.py
def htmldisplaytime(self):
time = self.created.strftime("%Y%m%d%H%M%S")
return time

Resources