Python 如何使用Django在数据库中存储request.POST值?

Python 如何使用Django在数据库中存储request.POST值?,python,django,sms,twilio,Python,Django,Sms,Twilio,我正在尝试存储发送到Twilio number的消息,因为它们是作为HTTP请求发送的,我想我可以通过request.POST获取参数值,但是我如何保存这些值并将它们存储在数据库中以便以后检索呢?这是我想出的代码,但它不起作用 views.py @csrf_exempt def incoming(request): from_ = request.POST.get('From') body_ = request.POST.get('Body') to_ = request

我正在尝试存储发送到Twilio number的消息,因为它们是作为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,因为它不会验证数据。如下所示:

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

并在视图中调用messageformsave方法进行保存。另外请注意,“to”字段是一个外键,值得一看

这听起来不错,特别是如果POST有效负载是可预测的(您知道要返回哪些字段)。我将创建一个模型来存储这些信息,并创建一个模型表单来验证/清理。如果要将此信息存储在其他位置,也可以跳过模型并简单地定义一个表单。
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)
from django import forms
class MessageForm(forms.ModelForm):
   class Meta:
      model = Message
      fields = '__all__'