首页 > 解决方案 > 在 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!!

标签: pythondjango

解决方案


您正在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)

推荐阅读