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

时间:2016-01-04 23:32:31

标签: python django sms twilio

我试图将发送到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)

1 个答案:

答案 0 :(得分:2)

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

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

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