检查以前的SMS发件人Django / Twilio

时间:2013-08-02 03:02:29

标签: python django twilio

我正在尝试跟踪向Twilio应用发送“密码”的用户的答案,以便他们回答一系列问题。首先,最好检查数据库中是否存在“from_number”,然后创建一个新的Caller(如果不存在)。

在models.py中:

class Callers(models.Model):
    body = models.CharField()
    from_number = models.CharField()
    last_question = models.CharField(max_length=1, default="0")

在views.py中:

def HelloThere(request):
    body = request.REQUEST.get('Body', None)
    from_number = request.REQUEST.get("From",None)

    if Caller.objects.filter(from_number == from_number):
        if last_question == "0":
            caller = Caller(message = "first question". last_question = "1")
            caller.save()
            return HttpResponse(str(resp))
        if last_question == '1':
            # so on and so forth
    else:
        caller = Caller(body=body, from_number=from_number, last_question='0')
        caller.save()
        message = "What is the password?"

我认为我不能使用request.user.is_authenticated()。

/拥有这么多相同的字段名称是不是一个坏主意? “身体=体=车身?

1 个答案:

答案 0 :(得分:0)

首先关于模型:

class Callers(models.Model):
    body = models.CharField()
    from_number = models.CharField()
    last_question = models.IntegerField(default=0) # if you have more than 10 question then I guess using IntegerField is better here

然后是观点:

def hello_there(request):  # this is a function, so use lower case with underscore for name
    body = request.REQUEST.get('Body', None)
    from_number = request.REQUEST.get("From",None)

    try:
        caller = Caller.objects.get(from_number=from_number) # using get() is better than filter here since I guess you want unique caller field in DB, right?
    except Caller.DoesNotExist:
        caller = None

    if caller:
        if caller.last_question == 0:
            # update the caller ?
            caller.last_question = 1
            caller.body = 'Something'
            caller.save()
            # ... your code ...
            return HttpResponse(str(resp))
        if last_question == 1:
            # so on and so forth
            # if you have repeated process here, make a function to update caller to be DRY
    else:
        new_caller = Caller(body=body, from_number=from_number, last_question=0)
        new_caller.save()
        message = "What is the password?"

request.user.is_authenticated()仅适用于User型号,因此您无法使用它。并且可以为不同的事物使用相同的名称,例如视图中的body可以是变量或参数。如果您不清楚那么您可以选择不同的名称。

希望它有所帮助!