数据未存储在django数据库中

zf9nrax1  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(98)

这是views.py中的代码。

def thanks(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        phone= request.POST['phone']
        doctor = request.POST['doctor']
        msg = request.POST['reason']
        print(name, email, phone, msg)
        appointment_db = appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg)
        appointment_db.save()
    return render(request, "thanks.html", {"name": name})

代码的其余部分正在工作。唯一的错误是在倒数第二和倒数第三行。

appointment_db = appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg)
        appointment_db.save()

这就是错误:

appointment_db = appointment(email=email, phone=phone, doctor=doctor, message=msg)
TypeError: appointment() got an unexpected keyword argument 'name'

这是模型:
从django.db导入模型

# Create your models here.
class appointment(models.Model):
    count=models.AutoField(primary_key=True)
    name= models.CharField(max_length=100)
    email= models.EmailField(max_length=1000)
    phone = models.IntegerField()
    message =models.TextField(max_length=5000)
    doctor = models.CharField(max_length=100)

    def __str__(self):
        return self.name + " | "+ "Doctor : "+ self.doctor

模型也已注册,并显示在管理面板中。但是,当我尝试通过表单在其中存储数据时,它会抛出错误。

c7rzv4ha

c7rzv4ha1#

你可能有一个同名的视图函数。因此,这意味着如果调用appointment(…),它将触发视图。
这就是为什么类通常用 PascalCase 编写的原因之一,所以Appointment而不是appointment

class Appointment(models.Model):
    count = models.AutoField(primary_key=True)
    # …

则视图因此与以下一起工作:

from django.views.decorators.http import require_POST

@require_POST
def thanks(request):
    name = request.POST['name']
    email = request.POST['email']
    phone = request.POST['phone']
    doctor = request.POST['doctor']
    msg = request.POST['reason']
    print(name, email, phone, msg)
    Appointment.objects.create(
        name=name, email=email, phone=phone, doctor=doctor, message=msg
    )
    return render(request, 'thanks.html', {'name': name})

注意:最好使用Form [Django-doc],而不是手动进行数据校验和清洗。Form不仅可以简化HTML中表单的渲染,还可以更方便地验证输入,并将数据清理为更方便的类型。
注意:如果POST请求成功,需要创建**redirect**[Django-doc]来实现Post/Redirect/Get pattern [wiki]。这样可以避免在用户刷新浏览器时发出相同的POST请求。

相关问题