Python 在Django视图中使用for循环覆盖ChoiceField choice属性

Python 在Django视图中使用for循环覆盖ChoiceField choice属性,python,django,Python,Django,我试图以可以循环查看视图中特定对象的形式覆盖ChoiceField, 但是我失败了,因为我只在模板表单中获取列表中的最后一项。。 需要一些帮助才能从这个对象获得我需要的所有选择 models.py class TourPackageBuyer(models.Model): tour = models.ForeignKey(TourPackage, on_delete=models.CASCADE, null =True) production number_choice =

我试图以可以循环查看视图中特定对象的形式覆盖ChoiceField, 但是我失败了,因为我只在模板表单中获取列表中的最后一项。。 需要一些帮助才能从这个对象获得我需要的所有选择

models.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
forms.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
views.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!!

每次通过循环时,您都要重新分配
选项的值,因此只有在循环完成后,您才能获得最后分配的值

您可以通过替换以下内容来修复此问题:

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)

非常感谢,我使用了列表理解,它对我起了作用。。