使用FormView时设置ChoiceField的选定值

问题描述 投票:0回答:1

我正在使用FormView显示一个表单,但是我需要在页面渲染时设置一个选定的ChoiceField,例如设置默认选择。

根据qazxsw poi,我需要:

在实例化表单时尝试设置初始值:

我不知道怎么做。我也尝试过sending initial = 1但没有成功

related Question

forms.朋友

class StepOneForm(forms.Form):
    size = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño', initial=1)
    quantity = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad')

views.朋友

class StepOneForm(forms.Form):
    size = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño')
    quantity = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad')


class StepTwoForm(forms.ModelForm):
    comment = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = CartItem
        fields = ('file', 'comment')

    def __init__(self, *args, **kwargs):
        super(StepTwoForm, self).__init__(*args, **kwargs)
        self.fields['comment'].required = False
        self.fields['file'].required = False

    def save(self, commit=True):
        instance = super(StepTwoForm, self).save(commit=commit)
        return instance

更新1:

class StepOneView(FormView):
    form_class = StepOneForm
    template_name = 'shop/medidas-cantidades.html'
    success_url = 'subir-arte'

    def get_initial(self):
        # pre-populate form if someone goes back and forth between forms
        initial = super(StepOneView, self).get_initial()
        initial['size'] = self.request.session.get('size', None)
        initial['quantity'] = self.request.session.get('quantity', None)
        initial['product'] = Product.objects.get(
            category__slug=self.kwargs['c_slug'],
            slug=self.kwargs['product_slug']
        )

        return initial

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['product'] = Product.objects.get(
            category__slug=self.kwargs['c_slug'],
            slug=self.kwargs['product_slug']
        )
        return context

    def form_invalid(self, form):
        print('Step one: form is NOT valid')

    def form_valid(self, form):
        cart_id = self.request.COOKIES.get('cart_id')
        if not cart_id:
            cart = Cart.objects.create(cart_id="Random")
            cart_id = cart.id
        cart = Cart.objects.get(id=cart_id)
        item = CartItem.objects.create(
            size=form.cleaned_data.get('size'),
            quantity=form.cleaned_data.get('quantity'),
            product=Product.objects.get(
                category__slug=self.kwargs['c_slug'],
                slug=self.kwargs['product_slug']
            ),
            cart=cart
        )

        response = HttpResponseRedirect(self.get_success_url())
        response.set_cookie("cart_id", cart_id)
        response.set_cookie("item_id", item.id)
        return response


# here we are going to use CreateView to save the Third step ModelForm
class StepTwoView(FormView):
    form_class = StepTwoForm
    template_name = 'shop/subir-arte.html'
    success_url = '/cart/'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['product'] = Product.objects.get(
            category__slug=self.kwargs['c_slug'],
            slug=self.kwargs['product_slug']
        )
        return context

    def form_invalid(self, form):
        print('StepTwoForm is not Valid', form.errors)

    def form_valid(self, form):
        item_id = self.request.COOKIES.get("item_id")

        cart_item = CartItem.objects.get(id=item_id)
        cart_item.file = form.cleaned_data["file"]
        cart_item.comment = form.cleaned_data["comment"]
        cart_item.step_two_complete = True
        cart_item.save()
        response = HttpResponseRedirect(self.get_success_url())
        response.delete_cookie("item_id")
        return response
django django-forms django-views formview
1个回答
0
投票

您正在考虑将第一个选择值设置为默认值,为此,您需要将初始值设置为您想要的值。

TAMANIOS = (('5cm x 5cm', '5 cm x 5 cm',), ('7cm x 7cm', '7 cm x 7 cm',), ('10cm x 10cm', '10 cm x 10 cm',), ('13cm x 13cm', '13 cm x 13 cm',)) CANTIDADES = (('50', '50',), ('100', '100',), ('200', '200',), ('300', '300',), ('500', '500',), ('1000', '1000',), ('2000', '2000',), ('3000', '3000',), ('4000', '4000',), ('5000', '5000',), ('10000', '10000',)) ,每个选项都是一个具有以下格式的元组:(值,表示)。

因此,要设置您想要的值作为初始值,您需要选择第一个选择的索引,从您的TAMANIOS选项中,第一个是Django's choices interface,因此初始值应为:('5cm x 5cm', '5 cm x 5 cm',)

下面显示了一个示例,其中包含结果的图片。

'5cm x 5cm'

class StepOneForm(forms.Form): size = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño', initial='5cm x 5cm') quantity = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad')

© www.soinside.com 2019 - 2024. All rights reserved.