[英]How to store request.POST values in database with Django?
I'm trying to store the messages sent to Twilio number and since they're sent as HTTP request, I thought I could get the parameters values with request.POST but how can I save these values and store them in a database for retrieval later? 我正在尝试存储发送到Twilio编号的消息,并且由于它们是作为HTTP请求发送的,所以我认为我可以通过request.POST获得参数值,但是如何保存这些值并将其存储在数据库中以供以后检索? Here's the code I've come up with but it doesn't work. 这是我想出的代码,但是没有用。
views.py 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')
The code work when I delete all the request.POST and database query 当我删除所有请求时,代码起作用。POST和数据库查询
@csrf_exempt
def incoming(request):
twiml = '<Response><Message>Hi</Message></Response>'
return HttpResponse(twiml, content_type='text/xml')
Here is the Message model from models.py 这是来自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)
The right way to save is to have a model form and call is_valid and save method on them. 正确的保存方法是拥有模型表单,然后调用is_valid并在其上保存方法。 Using request.POST is not advised, as it does not validate data. 不建议使用request.POST,因为它不会验证数据。 Something like below: 如下所示:
from django import forms
class MessageForm(forms.ModelForm):
class Meta:
model = Message
fields = '__all__'
and in your view call the MessageForm save method to save. 然后在您的视图中调用MessageForm save方法进行保存。 Also please note that 'to' field is a foreign key, it may be worth having look at How do I add a Foreign Key Field to a ModelForm in Django? 还请注意,“ to”字段是外键,可能值得一看“ 如何在Django中将外键字段添加到ModelForm”?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.