Juan Camilo Orjuela
Juan Camilo Orjuela

Reputation: 81

Django form is not creating new entries

I have the following form to create new clients on a database on Django and rendered using crispyforms. However, even thoug it is rendered correctly, it's not creating new entries.

models.py

class Client (models.Model):
    def __str__(self):
        return self.name + ' '+ self.surname
    name            = models.CharField(max_length=120)
    surname         = models.CharField(max_length=120, null=True)
    phone           = models.PositiveIntegerField(null=True)
    mail            = models.EmailField(null=True)
    sport           = models.TextField(blank=True, null=True)
    gender_options=(
        ("F", "femenino"),
        ("M", "masculino"),
        )
    gender          = models.CharField(max_length=120, null=True, choices=gender_options)
    birth           = models.DateField(null=True)

    def get_absolute_url(self):
        return reverse("clientes:cliente", kwargs={"client_id": self.id})
    pass

forms.py

from django import forms
from .models import Client

class NewClientForm(forms.Form):
    name    = forms.CharField(label='Nombres')
    surname = forms.CharField(label='Apellidos')
    phone   = forms.CharField(label='Teléfono')
    mail    = forms.EmailField(label='Correo electrónico')
    gender  = forms.ChoiceField(label='Género', choices= Client.gender_options)
    birth   = forms.DateField(label='Fecha de nacimiento', widget=forms.TextInput(attrs={
            'id': "datepicker",
        }))
    sport   = forms.CharField(label='Deportes')

views.py

def new_client_view(request):
    new_client_form = NewClientForm()
    if request.method == "POST":
        new_client_form = NewClientForm(request.POST)
        if new_client_form.is_valid():
            Client.objects.create(**new_client_form.cleaned_data)
        else:
            print(new_client_form.errors)
    context = {
    "form": new_client_form
    }
    return render (request, 'clients/new-client.html', context)

html

{% extends 'base.html' %}
{% load bootstrap4 %}


{% load crispy_forms_tags %}

{% block content %}
    <h1>Nuevo cliente</h1>
    <section class="container">
        <form action="." method="POST" class="form-floating mb-3"> {%csrf_token%}
            <div class="form-row">
                <div class="form-group col-md-6 mb-0">
                 {{ form.name|as_crispy_field }}
                </div>
                <div class="form-group col-md-6 mb-0">
                 {{ form.surname|as_crispy_field }}
                </div>
                 <div class="form-group col-md-6 mb-0">
                 {{ form.phone|as_crispy_field }}
                 </div>
                 <div class="form-group col-md-6 mb-0">
                 {{ form.mail|as_crispy_field }}
                 </div>
                 <div class="form-group col-md-6 mb-0">
                 {{ form.sport|as_crispy_field }}
                 </div>
                 <div class="form-group col-md-6 mb-0">
                 {{ form.gender|as_crispy_field }}
                 </div>
                 <div class="form-group col-md-6 mb-0">
                 {{ form.birth|as_crispy_field }}
                 </div>
            </div>
            

            <input class="btn btn-primary" type="submit" name="Save">
        </form>

    </section>
{% endblock content %}

Form is correctly rendered, but when the form is sent, no new entry is created. I can't get why. For me everything should be working.

Upvotes: 1

Views: 600

Answers (1)

Zahin Zaman
Zahin Zaman

Reputation: 260

I tried replicating your project twice, both times I had no issue copying your code directly. It works fine for me. I set up a couple of print statements in the view:

from django.shortcuts import render
from .forms import NewClientForm
from .models import Client

# Create your views here.
def new_client_view(request):
    new_client_form = NewClientForm()
    print('request method: ', request.method)
    if request.method == "POST":
        new_client_form = NewClientForm(request.POST)
        if new_client_form.is_valid():
            Client.objects.create(**new_client_form.cleaned_data)
            print('new client created')
        else:
            print(new_client_form.errors)
    context = {
    "form": new_client_form
    }
    return render (request, 'clients/new-client.html', context)

This is what I see on the new client form page:

new client form page

This is what I see on the command line as I visit the page and submit the form:

cmd line

As you can see, once I visit the page, the view receives a GET request, which makes sense, and which I see from your comment that you're seeing too. Once I hit "Submit" the view receives a POST request, which then creates a new Client object.

I used the Django shell to confirm that the Client object was indeed created:

django shell

So your code is fine, it may have something to do with the way you're filling up your form, or maybe a browser issue, I can't really tell.

Upvotes: 1

Related Questions