Login_Required Django不使用FormView

时间:2013-11-01 19:04:33

标签: python django login decorator formview

我有一个基本上是产品页面的FormView。您可以查看产品详细信息并从该页面上的表单中请求产品。我希望页面设置为任何人都可以查看该页面,但只有登录的人才能请求该产品。为此,我在FormView中的post函数中添加了一个login_required装饰器,但是我收到错误:

  

'QueryDict'对象没有属性'user'

如何对此视图/表单进行编码,使其按照我的描述进行操作?

查看:

class RedeemReward(SingleObjectMixin, FormView):
    template_name = 'reward.html'
    slug_field = 'reward_slug'
    form_class = Redeem_Reward
    model = Reward

    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):
        return super(RedeemReward, self).post(request, *args, **kwargs)

    def form_valid(self, form):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        #form = self.get_form(self.get_form_class())
        #form.save(self.request.POST)
        form.save(self.request.POST)
        return super(RedeemReward, self).form_valid(form)

    def get_success_url(self):
        return reverse('reward_confirmation', args=(self.object.reward_slug, self.object.reward_code))

    def dispatch(self, *args, **kwargs):
        self.object = self.get_object()
        return super(RedeemReward, self).dispatch(*args, **kwargs)

形式:

class Redeem_Reward(forms.Form):
    quantity = forms.IntegerField(label=_('Quantity'), error_messages={'invalid':'Must be a valid number'})
    reward_name = forms.CharField(max_length=50, widget=forms.HiddenInput(), label=_('Reward Name'), error_messages={'invalid':'Invalid reward'})
    def clean_quantity(self):
        """
        Validate that the user entered a valid number.
        """
        return self.cleaned_data['quantity']
    def clean_reward_name(self):
        """
        Validate that this reward code exists.
        """
        try:
            existing_reward = Reward.objects.get(reward_name=self.cleaned_data['reward_name'])
        except ObjectDoesNotExist:
            raise forms.ValidationError(_("The reward you requested does not exist."))
        return self.cleaned_data['reward_name']
    def save(self, request, *args, **kwargs):
        """
        Save all of the required data.
        """
        user = request.user
        #user_points = Points.objects.filter(affiliate__id=user.id).annotate(total_points=Sum('points'))
        user_points = Affiliate.objects.filter(points__affiliate__id=user.id).annotate(total_points=Sum('points'))
        user_points = user_points[0].total_points
        error_message = {'lookuperror':'You need to provide a valid quantity', 
                         'insufficient_points':"You don't have enough points for this purchase."}
        try:
            quantity = self.cleaned_data['quantity']
            reward_name = self.cleaned_data['reward_name']
            rewards = Reward.objects.get(reward_name=reward_name)
        except LookupError:
            raise Http404
        try:
            points_cost = -(rewards.reward_cost * quantity)
        except ArithmeticError:
            raise Http404
        quote_price = -(points_cost)
        if user_points >= quote_price:
            reward_order = Points.objects.create(affiliate=user, reward=rewards, points=points_cost, from_reward=True, from_offer=False, from_referral=False)
            status_cost = Status_Code.objects.create(short_name="Pending", name="The order is currently being reviewed", description="The order is in queue")
            redeem_order = Redeem.objects.create(affiliate=user, reward=rewards, status_code=status_code)
            redeem_details = Redeem_Details.objects.create(redeem=redeem_order, quantity=quantity, quote_price=quote_price)
            return HttpResponseRedirect(reverse('reward_confirmation', args=(redeem_details.redeem_code,)))
        else:
            return render(request, 'reward.html', {'error_message':error_message['insufficient_points']})

1 个答案:

答案 0 :(得分:1)

您正在将self.request.POST传递给表单的save方法,该方法设置为将请求作为其第一个参数。或者至少具有user属性的东西。如果您传入self.request,则不会再出现该错误。

您在form方法中重新验证form_valid是很奇怪的,该方法接收绑定表单作为参数。

您正在从表单的自定义保存方法返回HttpResponse个对象,这是非标准的。但只要您这样做,就应该从form_valid方法返回它们。

总之,这样的事情:

def form_valid(self, form):
    return form.save(self.request)