FGH
FGH

Reputation: 11

form.is_valid is always False. probably about ManyToManyField

I'm working on my first project in Django. The project has two applications. Each application has one model.

There is a Station model and an Employee model. Employees belong to multiple Stations, so there is a many-to-many relationship (ManyToManyField in Employee model: "belong_to").

/LedgerEmployee/
    models.py <- Employee model
/LedgerStation/
    models.py <- Station model

Problem

Validation is always false when POSTing a new LedgerEmployee registration form.

Additional Information

LedgerEmployee's new registration form was working fine (True) before "believe_to" was installed. I think it's probably a many-to-many error. (Even after the installation, I can register correctly in the /admin page, but I don't want other people to put it in /admin).

As I am not an engineer, I think you guys are making the code hard to read. Please please please help me.

/LedgerEmployee/models.py

from django.db import models

# Create your models here.
from django.conf import settings
from LedgerStation.models import Station

class Employee(models.Model):
    name_1 = models.CharField('name_1', max_length=20)
    name_2 = models.CharField('name_2', max_length=20)
    tel1 = models.CharField('tel11', max_length=13)
    tel2 = models.CharField('tel22', max_length=13, default='', blank=True)
    postal_code = models.CharField('postal_code', max_length=8, default='', blank=True)
    address = models.TextField('address', default='', blank=True)
    email = models.CharField('email', max_length=30, default='', blank=True)
    nurse_licence_type = models.CharField('nurse_licence_type', max_length=4, \
        choices=settings.NURSE_LICENCE_TYPE, default='None')
    nurse_licence_num = models.CharField('nurse_licence_num', max_length=10, default='', blank=True)
    nurse_licence_date = models.CharField('nurse_licence_date', max_length=10, default='', blank=True)
    belong_to = models.ManyToManyField(Station, verbose_name='belong', blank=True)
    memo = models.TextField('memo', default='', blank=True)

    created_at = models.DateTimeField('created_at', auto_now_add=True, editable=True)
    created_by = models.CharField('created_by', max_length=20, default='', blank=True)
    updated_at = models.DateTimeField('updated_at', auto_now=True, editable=True)
    updated_by = models.CharField('updated_by', max_length=20, default='', blank=True)

    class Meta:
        db_table = 'T_Employees'

    def __str__(self):
        return f'{self.pk}{self.name_1}'

/LedgerEmployee/views.py

def le_new(request):  # for register
    form = EmployeeForm(request.POST)
    if form.is_valid():  # Always False.
        employee = form.save(commit=False)
        employee.created_by = str(request.user.last_name) + ' ' + str(request.user.first_name)
        employee.save()
        return redirect(le_detail, employee_id=employee.pk)
    else:
        context = {'form': form}
        return render(request, 'LedgerEmployee/le_new.html', context)  # Registoration page.

/LedgerEmployee/forms.py

from django import forms
from LedgerEmployee.models import Employee

class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        # fields = ['name_1', 'name_2', 'tel1', 'tel2', 'postal_code', 'address', 'email', 'nurse_licence_type', 'nurse_licence_type', 'nurse_licence_num', 'nurse_licence_date', 'belong_to', 'memo',]  # I was tried, but not working.
        fields = '__all__'
        exclude = ('belong_to', 'created_at', 'created_by', 'updated_at', 'updated_by', )

/templates/LedgerEmployee/le_new.html <- registoration page

{% extends 'base.html' %}
{% block main %}
<form method='post mt-1'>
        {% csrf_token %}
        {{ form.as_p }}
        <button class='btn btn-primary' type='submit'>submit</button>
        <a class='btn btn-primary' href='{% url "le_top" %}'>return</a>
    </form>
{% endblock %}

/LedgerStation/models.py

from django.db import models

# Create your models here.
from django.conf import settings

class Station(models.Model):
    name_1 = models.CharField('name_1', max_length=50, default='')
    name_2 = models.CharField('name_2', max_length=50, default='')
    postal_code = models.CharField('postal_code', max_length=8)
    address = models.TextField('address')
    tel1 = models.CharField('tel1', max_length=13)
    tel2 = models.CharField('tel2', max_length=13, blank=True, default='')
    fax = models.CharField('Fax', max_length=13, blank=True, default='')
    memo = models.TextField('memo', default='', blank=True)

    created_at = models.DateTimeField('created_at', auto_now_add=True, editable=True)
    created_by = models.CharField('created_by', max_length=20, default='', blank=True)
    updated_at = models.DateTimeField('updated_at', auto_now=True, editable=True)
    updated_by = models.CharField('updated_by', max_length=20, default='', blank=True)

    class Meta:
        db_table = 'T_Stations'

    def __str__(self):
        return self.name_1

Additional

(0.004) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2021-10-08 13:54:47.332823' AND "django_session"."session_key" = 'guvgg58fs7b57ai9yik9t9moswbrldp9') LIMIT 21; args=('2021-10-08 13:54:47.332823', 'guvgg58fs7b57ai9yik9t9moswbrldp9')
(0.001) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 LIMIT 21; args=(1,)

[08/Oct/2021 22:43:34] "GET /LedgerEmployee/new/?csrfmiddlewaretoken=I7fFEpDGYJ9c8fJl6Z5ezk2lGqWNCvSss0eJm4wEHjWkQDuw2pjjwAPpLPQufrKI&name_kanji=test1&name_kana=test2&tel1=test&tel2=&postal_code=&address=&email=&nurse_licence_type=%E3%81%AA%E3%81%97&nurse_licence_num=&nurse_licence_date=&memo= HTTP/1.1" 200 3733

Upvotes: 1

Views: 126

Answers (1)

Bruno Urbano
Bruno Urbano

Reputation: 377

I believe what you should do is print(form.errors) so that you can see the errors that are being raised.

There is a error in the form method. You are writing

<form method='post mt-1'> 

instead of

<form method="post" class="mt-1">

You can see here that the view is receiving the method GET instead of POST

[08/Oct/2021 22:43:34] "GET /LedgerEmployee/new/?csrfmiddlewaretoken=I7fFEpDGYJ9c8fJl6Z5ezk2lGqWNCvSss0eJm4wEHjWkQDuw2pjjwAPpLPQufrKI&name_kanji=test1&name_kana=test2&tel1=test&tel2=&postal_code=&address=&email=&nurse_licence_type=%E3%81%AA%E3%81%97&nurse_licence_num=&nurse_licence_date=&memo= HTTP/1.1" 200 3733

Upvotes: 1

Related Questions