I am working on a small Transport planner app. I have a Model as follows.
I have four widgets to select, but I want to select only the store_name field and with this selection I want to set default values for the other three fields. It would be practical to set the default value for all with only one selection, because most of the cases I use this default value. The default values are in the Store Model.
Do you have any idea how can I do it?
Thank you in advance!
class StoreNumber(models.Model):
number = models.CharField(max_length=10, default=None)
def __str__(self):
return str(self.number)
class TransportCompany(models.Model):
name = models.CharField(max_length=100, default=None)
def __str__(self):
return self.name
class Store(models.Model):
name = models.CharField(max_length=100, default=None)
default_store_number = models.CharField(max_length=100, default=None)
default_company = models.ForeignKey(TransportCompany, null=True, on_delete=models.SET_NULL)
default_expedition_time = models.TimeField(default=None)
def __str__(self):
return str(self.name)
class Transport(models.Model):
store_name = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL)
store_number = models.ForeignKey(StoreNumber, null=True, on_delete=models.SET_NULL)
transport_company = models.ForeignKey(TransportCompany, null=True, on_delete=models.SET_NULL)
expedition_time = models.TimeField(default=None)
def __str__(self):
return str(self.expedition_time) + ' | ' + str(self.store_name) + ' | ' + str(self.store_number)
def get_absolute_url(self):
return reverse('transportplanner')
The form.py:
store_choices = Store.objects.all().values_list('name','name')
store_choice_list = []
for item in store_choices:
store_choice_list.append(item)
store_number_choices = StoreNumber.objects.all().values_list('number','number')
store_number_choice_list = []
for item in store_number_choices:
store_number_choice_list.append(item)
company_choices = TransportCompany.objects.all().values_list('name','name')
company_choice_list = []
for item in company_choices:
company_choice_list.append(item)
class TransportForm(forms.ModelForm):
class Meta:
model = Transport
fields = ('store_name', 'store_number', 'transport_company', 'expedition_time')
widgets = {
'store_name': forms.Select(choices=store_choice_list, attrs={'class': 'form-control'}),
'store_number': forms.Select(choices=store_number_choice_list, attrs={'class': 'form-
control'}),
'transport_company': forms.Select(choices=company_choice_list, attrs={'class': 'form-
control'}),
'expedition_time': TimePickerInput(attrs={'class': 'form-control'}, options=
{"enableTime": "true", "noCalendar": "true", "dateFormat": "H:i", "time_24hr": "true",
"defaultDate":"12:00"}),
}
question from:
https://stackoverflow.com/questions/65911383/django-default-values-depend-on-selected-value 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…