This is the code in 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})
rest of the code is working. the only error is in the second-last and third-last line.
appointment_db = appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg)
appointment_db.save()
this is the error:
appointment_db = appointment(email=email, phone=phone, doctor=doctor, message=msg)
TypeError: appointment() got an unexpected keyword argument 'name'
this is the model:
from django.db import models
# 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
The model is also registered and it is showing in the admin panel. However, when I try to store data in it via forms, it throws an error.
>Solution :
Likely you have a view function with the same name. This thus means that if you call appointment(…), it triggers the view instead.
This is one of the reasons why classes are normally written in PascalCase, so Appointment instead of :appointment
class Appointment(models.Model):
count = models.AutoField(primary_key=True)
# …
then the view thus works with:
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})
Note: It is better to use a
Form[Django-doc]
than to perform manual validation and cleaning of the data. AFormwill not
only simplify rendering a form in HTML, but it also makes it more convenient
to validate the input, and clean the data to a more convenient type.
Note: In case of a successful POST request, you should make a
redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.