Form Validation Check

Please guide me where to insert the is_valid() in below views.py code. I want to enable the form validation in my code. I am not using this line ‘’‘{{form.as_p}}’‘’ in my template.

Views.py:

def OwnerCreate(request):
  if request.method == "POST":
    newOwner = Owner()
    newOwner.first_name = request.POST["firstNameField"]
    newOwner.last_name = request.POST["lastNameField"]
    newOwner.phone = request.POST["phoneNumField"]
    newOwner.save()
  return render(request, "owner_create_form.html")

I have attached the template.

Side note: Please do not post images of code or templates here. Copy/paste the text into the body of your post surrounded between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code (or template), then another line of ```.
(The lines of ``` must be lines on their own, then must not be part of other lines. Also, you must use the backtick - ` and not the apostrophe - '. I’ve fixed the code portion of your post for you for this.)

Then use a form.

Start with reviewing the page and the examples at Working with forms | Django documentation | Django.

Then read Creating forms from models | Django documentation | Django and Form and field validation | Django documentation | Django

I did some homework and following is the code. Please highlight any mistake or can be done in other better way.

views.py:
def OwnerCreate(request):
  if request.method == "POST":
    form = OwnerCreateForm(request.POST)
    if form.is_valid():
      form = form.save()
      messages.success(request, "Account created successfully")
      return redirect("ownerlist")
  else:
    form = OwnerCreateForm()
    return render(request, "form/owner_create_form.html", {"form":form})

urls.py:
urlpatterns = [
   path('', views.home, name="home"),
   path('ownerlist', views.OwnerList.as_view(), name="ownerlist"),
   path('ownercreate', views.OwnerCreate, name="ownercreate"),
]

forms.py:
class OwnerCreateForm(forms.ModelForm):
    class Meta:
        model = Owner
        fields = ('first_name', 'last_name', 'phone')

Template: owner_create_form.html
<form action="" method="post">
  {% csrf_token %}
  {{form.as_p}}
<input type="submit" value="Submit">
</form>

models.py:
class Owner(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    phone = models.CharField(max_length=30)

    def get_absolute_url(self):
        return "ownerlist"

Almost perfect. Just two things I’d want to point out.

First, look at what’s going to happen if the test form.is_valid() is false. You have no else clause on that if, and there is no code at the level of the if request.method below its else. This means the function would return None, which isn’t valid for a view. (It would throw an error.)

If you look again at the example view in the “Working with Forms” docs, you’ll see that the return render(...) statement is outside the bounds of the if statements so that it will be called in both of those conditions (When either form.is_valid() is False or when request.method is not ‘POST’.)

The other suggestion is that you adhere to the Python and Django coding conventions - function names are lowercase. Only class names are capitalized. This would make your function name owner_create, with the corresponding change in your urls.py file.

Noted. Thanks a lot Ken.