【问题标题】:How to store request.POST values in database with Django?如何使用 Django 在数据库中存储 request.POST 值?
【发布时间】:2016-04-08 16:38:16
【问题描述】:

我正在尝试存储发送到 Twilio 号码的消息,因为它们是作为 HTTP 请求发送的,所以我想我可以使用 request.POST 获取参数值,但是如何保存这些值并将它们存储在数据库中以后检索?这是我想出的代码,但它不起作用。

views.py

@csrf_exempt
def incoming(request):
    from_ = request.POST.get('From')
    body_ = request.POST.get('Body')
    to_ = request.POST.get('To')
    m = Message.objects.create(sentfrom=from_, content=body_, to=to_)
    m.save()
    twiml = '<Response><Message>Hi</Message></Response>'
    return HttpResponse(twiml, content_type='text/xml')

当我删除所有 request.POST 和数据库查询时代码工作

@csrf_exempt
def incoming(request):
    twiml = '<Response><Message>Hi</Message></Response>'
    return HttpResponse(twiml, content_type='text/xml')

这是来自 models.py 的消息模型

class Message(models.Model):
    to = models.ForeignKey(phoneNumber, null=True)
    sentfrom = models.CharField(max_length=15, null=True)
    content = models.TextField(null=True)

    def __str__(self):
        return '%s' % (self.content)

【问题讨论】:

    标签: python django sms twilio


    【解决方案1】:

    正确的保存方法是有一个模型表单并调用 is_valid 和保存方法。不建议使用 request.POST,因为它不验证数据。如下所示:

    from django import forms
    class MessageForm(forms.ModelForm):
       class Meta:
          model = Message
          fields = '__all__'
    

    并在您的视图中调用 MessageForm 保存方法进行保存。另请注意,'to' 字段是外键,可能值得一看 How do I add a Foreign Key Field to a ModelForm in Django?

    【讨论】:

    • 这听起来很对,尤其是如果 POST 有效负载是可预测的(您知道要返回哪些字段)。我会创建一个模型来存储这些信息,并创建一个模型表单来验证/清理。如果您将此信息存储在其他地方,您也可以跳过模型并简单地定义一个表单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2014-09-25
    • 2021-09-05
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多