将request.POST保存到数据库

时间:2017-01-17 18:04:22

标签: django django-models django-forms django-views

view.py:

中的

@require_POST
@csrf_exempt
def ipn(request):
    transactions_logger = logging.getLogger("django")
    processor = Ipn(request.POST, logger=transactions_logger)
    verification_success = processor.verify_ipn()
    encoding = request.POST.get('ok_charset', None)
    data = QueryDict(request.body, encoding=encoding)
    if verification_success:
        form = OkpayIpnForm(data)
        if form.is_valid():
            print("ALL FINE!!")
            form.save()

    return HttpResponse("")

forms.py:

 class OkpayIpnForm(forms.ModelForm):

    class Meta:
        model = OkpayIpn
        exclude = []

IPN代码检查processor = Ipn(request.POST, logger=transactions_logger

class Ipn(object):


   OKPAY_VERIFICATION_URL = 'https://checkout.okpay.com/ipn-verify'
   OKPAY_IPN_INVALID = b'INVALID'
   OKPAY_IPN_VERIFIED = b'VERIFIED'
   OKPAY_IPN_TEST = b'TEST'
   OKPAY_STATUS_COMPLETED = 'completed'

   __verification_result = False

   def __init__(self, request_data, logger):
      if 'ok_verify' in request_data:
        raise Exception("ok_verify must not be present in initial request data for {}".format(
            self.__class__.__name__
        ))
      self._request_data = request_data
      self.logger = logger
      return

   def verify_ipn(self):
       self.__verification_result = False
       headers = {
           'Content-Type': 'application/x-www-form-urlencoded',
       }
       verify_request_payload = {
           'ok_verify': 'true',
       }
       verify_request_payload.update(self._request_data)

       resp = requests.post(self.OKPAY_VERIFICATION_URL, data=verify_request_payload, headers=headers)

       if resp.content == self.OKPAY_IPN_VERIFIED or resp.content == self.OKPAY_IPN_TEST:
        self.__verification_result = True
       # if resp.content == self.OKPAY_IPN_VERIFIED:  # anyway disable test on production.
       #     self.__verification_result = True
       return self.__verification_result

一切正常,我修改IPN并验证它,然后我尝试验证表单并将其保存到数据库。

但表格没有通过验证,也没有保存到数据库。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

问题是用于保存IPN的1 CharField模型有maxlength=20,但收到了40个符号。

Thx jape他建议添加表单验证else语句并打印form.errors

表单验证的错误是:

<li>ok_item_1_type<ul class="errorlist"><li>Ensure this value has at most 20 characters (it has 40).</li></ul></li>