form.is_valid()是为什么?

时间:2016-01-08 00:50:04

标签: python django sms twilio

我想将POST请求存储到数据库,所以我有一个模型表单MessageForm并从视图中调用它来验证数据并保存它。

models.py

class phoneNumber(models.Model):
    address = models.CharField(max_length=15)

    def __str__(self):
        return self.address


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)

forms.py

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

    def __init__(self, *args, **kwargs):
        to = kwargs.pop('to', '')
        super(MessageForm, self).__init__(*args, **kwargs)
        self.fields['to']=forms.ModelChoiceField(queryset=phoneNumber.objects.filter(address=to))

views.py

@csrf_exempt
def incoming(request):
    if request.method == "POST":
        form = MessageForm(request.POST)
        if form.is_valid():
            twiml = '<Response><Message>Yes</Message></Response>'
        else:
            twiml = '<Response><Message>No</Message></Response>'
    else:
        twiml = '<Response><Message></Message></Response>'
    return HttpResponse(twiml, content_type='text/xml')

没有任何内容保存,我在测试时得到No响应。

2 个答案:

答案 0 :(得分:2)

您可以在views.py

中访问错误
@csrf_exempt
def incoming(request):
    if request.method == "POST":
        form = MessageForm(request.POST)
        if form.is_valid():
            twiml = '<Response><Message>Yes</Message></Response>'
        else:
            print(form.errors)
            print(form.non_field_errors)
            twiml = '<Response><Message>No</Message></Response>'
    else:
        twiml = '<Response><Message></Message></Response>'
    return HttpResponse(twiml, content_type='text/xml')

答案 1 :(得分:1)

你试过了吗?

def __init__(self, *args, **kwargs):
    to = kwargs.pop('to', '')
    super(MessageForm, self).__init__(*args, **kwargs)
    self.fields['to'].queryset = phoneNumber.objects.filter(address=to)

此外,我不确定您是否要在views方法中向表单传递任何内容,因为现在您的to形式为空字符串,因此您的查询集正在查询phoneNumber.objects.filter(address=''),可能是也可能不是你想要的。

修改

to为空字符串的原因是kwargs.pop('to', '')表示从kwargs中弹出参数to,如果to不存在则默认为'' ”。在您的观点中,您可以:

form = MessageForm(request.POST)

但是您没有使用任何to参数提供构造函数,因此kwargs.pop('to', '')会将''作为默认值。您可能需要以下内容:

form = MessageForm(request.POST, to="white house")