我有两个模型Fleet和Ship,船舶是Fleets的ForeignKey字段:
class Fleet(models.Model):
fleet_ship_n_01 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_01', blank=True)
fleet_ship_n_02 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_02', blank=True)
fleet_ship_n_03 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_03', blank=True)
运输本身也有很多字段,例如:
class Ship(models.Model):
ship_class = models.CharField(default='NoClass', max_length=200, help_text="Ship class")
ship_tech_level = models.CharField(default=5, max_length=100, choices=tech_level)
ship_mass = models.PositiveIntegerField(default=0, help_text="Ship mass")
我有一个更新视图,其中我将舰队添加到舰队:
class UVFleetDetails(UpdateView):
template_name = 'fading_thrust/fleet_details_form.html'
model = Fleet
form = FleetForm()
total_ship_mass = 0
fields = ('fleet_ship_n_01', 'fleet_ship_n_02', 'fleet_ship_n_03', 'fleet_ship_n_04', 'fleet_ship_n_05',
'fleet_ship_n_06', 'fleet_ship_n_07', 'fleet_ship_n_08', 'fleet_ship_n_09', 'fleet_ship_n_10', )
def form_valid(self, form):
fleet = form.save()
fleet_id = self.kwargs['pk']
fleet.fleet_id = fleet_id
fleet.save()
return redirect('fleet_details', pk=fleet_id)
这是它的形式:
class FleetForm(ModelForm):
fleet_ship_n_1 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_2 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_3 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_4 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_5 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_6 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_7 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_8 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_9 = forms.ModelChoiceField(Ship.objects.all(), required=False)
fleet_ship_n_10 = forms.ModelChoiceField(Ship.objects.all(), required=False)
class Meta:
model = Fleet
fields = ('fleet_ship_n_01', 'fleet_ship_n_02', 'fleet_ship_n_03', 'fleet_ship_n_04', 'fleet_ship_n_05',
'fleet_ship_n_06', 'fleet_ship_n_07', 'fleet_ship_n_08', 'fleet_ship_n_09', 'fleet_ship_n_10',)
现在将舰队添加到舰队时,我还想显示有关这些舰队的重要详细信息。像ship_class,ship_tech_level,ship_mass等。但是我在模板中无法访问它。 以下是我的模板的一部分:
{% for field in form %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ field }}</td>
<td> ??? How to display ship mass ???</td>
</tr>
{% endfor %}