Django:验证GET参数

时间:2018-11-29 10:43:23

标签: python django

我在结帐时提供折扣代码。我创建了一个表单,用户可以在其中输入折扣代码,然后单击“应用”。表单会检查折扣代码是否有效,然后将其应用。

现在,我想添加要添加到url domain.com/event/?discount=ABC中的功能

我想检查是否设置了request.GET,然后以某种方式将其重定向到“表单” /将其转换为request.POST,以便进行验证。我目前正在努力寻找正确的方法来做到这一点。您对我如何使用GET-parameter并以与使用表单相同的方式进行验证有任何建议吗?

views.py

def dispatch(self, request, *args, **kwargs):
    # Provide discount_code to all functions
    self.discount_code = None

    # Check if discount code is saved as a session
    self.discount_code_session = request.session.get(
        request.event.discount_code_cookie(), None)
    if self.discount_code_session:
        self.discount_code = Discount.objects.filter(
            code=self.discount_code_session,
            event=self.request.event.pk
        ).first()

@transaction.atomic
def post(self, request, *args, **kwargs):

    # Discount Code
    if self.discount_form.is_valid():
        discount_code = self.discount_form.cleaned_data['code']
        request.session[request.event.discount_code_cookie()] = discount_code
        return redirect('events:detail', request.organizer.slug, request.event.slug)

forms.py

class DiscountFormEventPage(forms.ModelForm):
    # Remove required attribute from HTML elements
    use_required_attribute = False
    class Meta:
        model = Discount
        fields = (
            'code',
        )
    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super().__init__(*args, **kwargs)
        for visible_field in self.visible_fields():
            visible_field.field.widget.attrs['class'] = 'form-control'
    def clean_code(self):
        input_code = self.cleaned_data['code']
        # Check if discount code exists
        discount_code = self.event.discounts.filter(code=input_code).first()
        if not discount_code:
            raise forms.ValidationError(_("The discount code couldn't be found."),
                                        code='code_exists')
        elif not discount_code.is_active():
                raise forms.ValidationError(_("This discount code is not available\
                                               anymore."),
                                            code='code_not_active')
        return input_code

更新:

我现在在我的view.py(DetailView)中将其添加到这里:

def get(self, request, *args, **kwargs):

    discount_code_get = request.GET.get('code')
    if discount_code_get:
        return DiscountFormEventPage(
            prefix='discount',
            data=request.GET,
            event=self.request.event,
        )

2 个答案:

答案 0 :(得分:2)

我看不到您在哪里获取参数,这是您的问题所在吗?您可以按以下方式获取它:

# request.GET is a dict-like object
code = request.GET['discount']
# safer alternative against KeyError
code = request.GET.get('discount')
# if discount may be specified multiple times
code = request.GET.getlist('discount')

如果要使用表单来验证传入的数据,则应该能够将其作为第一个参数传递:

form = DiscountFormEventPage(request.GET)
if form.is_valid():
     data = form.cleaned_data
     return redirect('events:detail', request.organizer.slug, request.event.slug)

答案 1 :(得分:0)

我现在可以使用此代码解决它。感谢Bruno帮助我找到正确的轨道:

def get(self, request, *args, **kwargs):
    # Apply discount via GET parameter ?code=DISCOUNT
    discount_code_get = request.GET.get('code')
    if discount_code_get:
        self.discount_form = DiscountFormEventPage(
            data=request.GET,
            event=self.request.event,
        )
    if self.discount_form.is_valid():
        discount_code = self.discount_form.cleaned_data['code']
        request.session[request.event.discount_code_cookie()] = discount_code
        return redirect('events:detail', request.organizer.slug, request.event.slug)
    return super().get(request, *args, **kwargs)