I am trying to pass data through from a form depending on different calculations from the form submission
Full Model
from django.db import models
from datetime import datetime, date
# Create your models here.
year_choice = [
('year1','1-Year'),
('year3','3-Year')
]
weeksinyear = 52
hours = 6.5
class AdminData(models.Model):
year1 = models.IntegerField()
year3 = models.IntegerField()
@property
def day_rate_year1(self):
return self.year1 / weeksinyear / hours
@property
def day_rate_year3(self):
return self.year3 / weeksinyear / hours
class Price(models.Model):
name = models.CharField(max_length=100)
contract = models.CharField(max_length=5, choices=year_choice)
start_date = models.DateField(default=datetime.now)
end_date = models.DateField(default=datetime(2021,3,31))
epoch_year = date.today().year
year_start = date(epoch_year, 1, 4)
year_end = date(epoch_year, 3 , 31)
def __str__(self):
return self.name
@property
def pricing(self):
price_days = self.start_date - self.year_end
return price_days
Views
def price_detail(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = PriceForm(request.POST)
# check whether it's valid:
if form.is_valid():
form.save()
return render(request,'confirmation.html',{'form_data': form.cleaned_data})
else:
form = PriceForm()
return render(request, 'main.html', {'form': form})
So the idea is to change show details on the confirmation.html page depending on the contract type and start date, a basic but most like incorrect example is below:
def pricingcalc(request):
if PriceForm.contract == 'year1'
return Price.pricing * AdminData.day_rate_year1
else
return Price.pricing * AdminData.day_rate_year3
To summarise:
Hope this makes sense.
Thanks for the help.
If we look in documentation at how Model Forms work (more precisely here) we can see that once we call .save()
on a ModelForm
we'll get back an instance of that model.
In your case we can assume the following:
if form.is_valid():
price_instance = form.save()
Now, if you want to display some dynamic computed values for your pricing model, you can add a method on your Price
model that calculates them based on Price.contract
.
The important idea here is that once a ModelForm
is deemed valid
and you call .save()
on it, this will commit by default data in your database and return an instance of that model that you can use afterwards.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments