Django试图在保存到另一个模型后将数据保存到新模型中

时间:2017-08-31 22:23:44

标签: python django

嗨大家好我在过去的3天里一直在努力工作:

我无法在localhost上测试,因为支付网关需要在实时服务器上。

数据会保存到payfast模型,但不会保存到预订模型

我的代码如下

预订视图

class ViewBookingSummery(LoginRequiredMixin, FormView):
    login_url = '/login/'

    def get(self, request, slug, pk, guests):
        if pk:
            events_data = Events.objects.get(pk=pk)
            user = User.objects.get(pk=request.user.id)
            if events_data:
                formset = EventBookingForm()
                forms = PayFastForm(initial={
                    # required params:
                    'amount': int(events_data.price) * int(guests),
                    'item_name': events_data.title,
                    'name_first': user.first_name,
                    'name_last': user.last_name,
                    'email_address': user.email,

                    'custom_str1': user.id,
                    'custom_str2': events_data.id,
                    'custom_str3': events_data.date,
                    'custom_str4': guests,

                    # optional params:
                    'return_url' : settings.DOMAIN_NAME + '/bookings/',
                    'cancel_url' : settings.DOMAIN_NAME + '/booking-summery/' + slug + '/' + pk + '/' + guests + '/'
                    # ... etc.
                }, user=user)

                context = {'events_data': events_data, 'guests': guests, 'formset': formset, 'forms': forms}
                return render(request, 'bookings/booking-summery.html', context)
            else:
                return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect('/')

我的支付网关模型(成功付款后保存在数据库中)

class PayFastOrder(models.Model):

    # see http://djangosnippets.org/snippets/2180/
    __metaclass__ = readable_models.ModelBase

    # Transaction Details
    m_payment_id = models.AutoField(primary_key=True)
    pf_payment_id = models.CharField(max_length=40, unique=True, null=True, blank=True)
    payment_status = models.CharField(max_length=20, null=True, blank=True)
    item_name = models.CharField(max_length=100)
    item_description = models.CharField(max_length=255, null=True, blank=True)
    amount_gross = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True)
    amount_fee = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True)
    amount_net = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True)

    # The series of 5 custom string variables (custom_str1, custom_str2...)
    # originally passed by the receiver during the payment request.
    custom_str1 = models.CharField(max_length=255, null=True, blank=True)
    custom_str2 = models.CharField(max_length=255, null=True, blank=True)
    custom_str3 = models.CharField(max_length=255, null=True, blank=True)
    custom_str4 = models.CharField(max_length=255, null=True, blank=True)
    custom_str5 = models.CharField(max_length=255, null=True, blank=True)

    # The series of 5 custom integer variables (custom_int1, custom_int2...)
    # originally passed by the receiver during the payment request.
    custom_int1 = models.IntegerField(null=True, blank=True)
    custom_int2 = models.IntegerField(null=True, blank=True)
    custom_int3 = models.IntegerField(null=True, blank=True)
    custom_int4 = models.IntegerField(null=True, blank=True)
    custom_int5 = models.IntegerField(null=True, blank=True)

    # Payer Information
    name_first = models.CharField(max_length=100, null=True, blank=True)
    name_last = models.CharField(max_length=100, null=True, blank=True)
    email_address = models.CharField(max_length=100, null=True, blank=True)

    # Receiver Information
    merchant_id = models.CharField(max_length=15)

    # Security Information
    signature = models.CharField(max_length=32, null=True, blank=True)

    # Utility fields
    created_at = models.DateTimeField(default=datetime.now)
    updated_at = models.DateTimeField(default=datetime.now)
    request_ip = models.GenericIPAddressField(null=True, blank=True)
    debug_info = models.CharField(max_length=255, null=True, blank=True)
    trusted = models.NullBooleanField(default=None)
    user = models.ForeignKey(User, null=True, blank=True)

我的预订模式

class Bookings(models.Model):
    OPTIONS_STATUS = (
        ('y', "Yes"), 
        ('n', "No"), 
        ('p', "Pending")
    )
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    event = models.ForeignKey(Events, on_delete=models.CASCADE)
    eventdate = models.DateField()
    event_amount = models.CharField(max_length=50, blank=True, default='')
    guests = models.CharField(max_length=50, blank=True, default='')
    bookingstatus = models.CharField(max_length=50, default='p', blank=True, choices=OPTIONS_STATUS)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    class Meta:
        app_label = 'bookings'
        verbose_name = _("Bookings")
        verbose_name_plural = _("Bookings")

付款完成后,代码运行

def notify_handler(request):
    """
    Notify URL handler.

    On successful access 'payfast.signals.notify' signal is sent.
    Orders should be processed in signal handler.
    """

    id = request.POST.get('m_payment_id', None)
    order = get_object_or_404(PayFastOrder, pk=id)

    form = NotifyForm(request, request.POST, instance=order)
    if not form.is_valid():
        errors = form.plain_errors()[:255]
        order.request_ip = form.ip
        order.debug_info = errors
        order.trusted = True
        order.save()
        raise Http404

    order = form.save()

    obj = Bookings()  # gets new object
    obj.user_id = int(request.POST.get('custom_str1', None))
    obj.event_id = int(request.POST.get('custom_str2', None))
    obj.eventdate = '1992-03-17'
    obj.event_amount = '600'
    # finally save the object in db
    obj.save()

    signals.notify.send(sender=notify_handler, order=order)

    return HttpResponse()

由于某种原因,这不起作用

obj = Bookings()  # gets new object
obj.user_id = int(request.POST.get('custom_str1', None))
obj.event_id = int(request.POST.get('custom_str2', None))
obj.eventdate = '1992-03-17'
obj.event_amount = '600'
# finally save the object in db
obj.save()

如何从表单中获取要在预订模型中显示的值

1 个答案:

答案 0 :(得分:1)

我可以看到您在预订模型中保存obj的最终代码,您需要注意以下事项。

  1. 确保下面的代码行应该返回一个可解析的int字符串而不是None或任何随机字符串 user event 不是的可空字段预订模型

    request.POST.get('custom_str1', None)
    request.POST.get('custom_str2', None)
    
  2. 由于 eventdate 字段是DateField,因此它不会接受您传递的任何日期字符串。

      

    注意:格式字符串使用Python的datetime模块语法。

    对于你的情况,它看起来像。

    datetime.strptime('1992-03-17','%Y-%m-%d')
    
  3. 有关详细信息,请访问https://docs.djangoproject.com/en/1.8/ref/settings/#date-input-formats