NOT NULL constraint failed: store_customer.first_name
Request Method: GET
Request URL: http://127.0.0.1:8000/signup/
Django Version: 4.1.4
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: store_customer.first_name
models.py
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=500)
def register(self):
self.save()
def __str__(self):
return self.first_name
views.py
def signup(request):
if request == 'GET':
return render(request, 'signup.html')
else:
first_name = request.POST.get('firstname')
last_name = request.POST.get('lastname')
phone = request.POST.get('phone')
email = request.POST.get('email')
password = request.POST.get('password')
customer = Customer(first_name=first_name, last_name=last_name,phone=phone,email=email,password=password)
customer.register()
# return HttpResponse( 'signup successful' )
return render(request, 'signup.html')
CodePudding user response:
Are you sending first name in the form? By default 'models.CharField' has a null and 'blank' option set to false Django ref. - this means that the it need to be set to something different that null when saving.
Your error suggests that the first_name was not sent in POST request (from form).
CodePudding user response:
No need to handle GET
requests it's automatically handled by Django Just handle POST
requests like this...
models.py
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=500)
def __str__(self):
return self.first_name
views.py
def signup(request):
if request == 'POST': #<------- handled POST request
first_name = request.POST.get('firstname')
last_name = request.POST.get('lastname')
phone = request.POST.get('phone')
email = request.POST.get('email')
password = request.POST.get('password')
customer = Customer(first_name=first_name, last_name=last_name,phone=phone,email=email,password=password)
customer.save()
return redirect('/signup/')
return render(request, 'signup.html') #<------- handled GET request