I am trying to add new record into customer table via django forms but new records are not getting in the table also view function not redirecting to correct url.
Here is my model.py
class Customer(models.Model):
id = models.PositiveSmallIntegerField(primary_key=True)
name = models.CharField(max_length=200)
category = models.CharField(max_length=1)
def __str__(self) -> str:
return self.name
here are my url patterns
urlpatterns = [
path("create-customer" , views.create_customer , name = "create-customer"),
path("<str:n>" , views.customer_index , name="cust_index"),
path("" , views.home , name = "home"),
]
here are my views
def create_customer(response):
if response.method == "POST":
cust_form = createNewCustomer(response.POST)
if cust_form.is_valid():
i = cust_form.cleaned_data["id"]
n = cust_form.cleaned_data["name"]
cat = cust_form.cleaned_data["category"]
r = Customer(id = i , name = n , category = cat)
r.save()
return HttpResponseRedirect("%s" %r.n)
else:
cust_form = createNewCustomer()
return render(response , "main/create-customer.html" , {"form" : cust_form})
def customer_index(response, n):
cust = Customer.objects.get(name=n)
return render(response , "main/display_cust_det.html" , {"cust":cust})
and here is my form
class createNewCustomer(forms.Form):
id = forms.IntegerField(label = "id")
name = forms.CharField(label="name" , max_length=200)
category = forms.CharField(label="category" , max_length=1)
here are templates
{%extends "main/base.html"%}
{% block content %}
<h1>create customer</h1>
<form method="Post" , action="create">
{%csrf_token%}
{{form.as_p}}
<button type="Submit">Create Customer</button>
</form>
{% endblock %}
now when I am creating the customer it does not putting it into the customer table
CodePudding user response:
You need to catch error which you are submitting. For that, update your view like this:
def create_customer(response):
if response.method == "POST":
cust_form = createNewCustomer(response.POST)
if cust_form.is_valid():
... # same code as yours
else:
return render(response , "main/create-customer.html" , {"form" : cust_form})
else:
...
Also, update the html form as well to this:
<form method="post" action="create-customer">
You can check this tutorial about how to catch form errors in Geeksforgeeks tutorial.