2

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

在模型.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()。

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

4

1 回答 1

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在您的视图中可以是变量或参数。如果您不清楚,那么您可以选择不同的名称。

希望能帮助到你!

于 2013-08-02T09:04:58.093 回答