python - 在 Django 视图中使用 for 循环覆盖 ChoiceField 选择属性
问题描述
我试图在表单中覆盖 ChoiceField,我可以在其中循环遍历视图中的特定对象,但我失败了,因为我只进入模板表单,只有列表中的最后一项。需要一些帮助来获得我需要的所有选择从这个对象。
模型.py
class TourPackageBuyer(models.Model):
tour = models.ForeignKey(TourPackage, on_delete=models.CASCADE, null =True) production
number_choice = [(i,i) for i in range(6)]
number_choice_2 = [(i,i) for i in range(18)]
number_choice_3 = [(i,i) for i in range(60)]
user = models.CharField(settings.AUTH_USER_MODEL, max_length=200)
num_of_adults = models.PositiveIntegerField(default=0, choices= number_choice_2, null=True)
num_of_children = models.PositiveIntegerField(default=0, choices= number_choice_3, null=True)
hotel = models.ManyToManyField(PackageHotel, blank=True)### thats the field
表格.py
class TourPackageBuyerForm(ModelForm):
class Meta:
model = TourPackageBuyer
date = datetime.date.today().strftime('%Y')
intDate = int(date)
limitDate = intDate + 1
YEARS= [x for x in range(intDate,limitDate)]
# YEARS= [2020,2021]
Months = '1',
# fields = '__all__'
exclude = ('user','tour','invoice','fees', 'paid_case')
widgets = {
'pickup_date': SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day")),
'hotel': Select(),
# 'pickup_date': forms.DateField.now(),
}
hotel = forms.ChoiceField(choices=[]) ### Thats the field i m trying to override
视图.py
def TourPackageBuyerView(request, tour_id):
user = request.user
tour = TourPackage.objects.get(id=tour_id)
tour_title = tour.tour_title
hotels = tour.hotel.all()
form = TourPackageBuyerForm(request.POST or None, request.FILES or None)
### im looping through specific items in the model in many to many field
for h in hotels:
form.fields['hotel'].choices = (h.hotel, h.hotel), ### when this loop it just give the last item in the form in my template!!
解决方案
您正在choices
通过循环重新分配每次的值,因此您只会在循环完成后获得您分配的最后一个值。
您可以通过替换这个来解决这个问题:
for h in hotels:
form.fields['hotel'].choices = (h.hotel, h.hotel),
有了这个列表理解:
form.fields['hotel'].choices = [(h.hotel, h.hotel) for h in hotels]
或者如果你想要一个元组作为输出,你可以这样做:
form.fields['hotel'].choices = tuple((h.hotel, h.hotel) for h in hotels)
推荐阅读
- android - 显示来自谷歌驱动器的 pdf 文件
- c# - 为什么终止 for 循环会导致 NavMeshAgent 开始更快地移动?
- java - 多线程矩阵乘法性能问题
- bash - Batch renaming files on command line
- php - Access-Control-Allow-Origin SESSION 仅在 localhost 中无任何作用
- python - Python setuptools:首先从源代码构建然后安装
- javascript - 克隆多个图像javascript
- elasticsearch - 在关键字字段中拆分时出现运行时错误
- google-cloud-storage - 无需离开云端即可使用 Google Cloud Tar
- android - Android Studio 无法查看我的设备