django 异常值:"'" Sunday "值的日期格式无效,它必须为YYYY-MM-DD格式,']

ddrv8njm  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(120)

我正在尝试保存Attendance模式,但遇到错误。我无法确定它是什么。
错误为['“Sunday” value has an invalid date format. It must be in YYYY-MM-DD format.']
这是我的models.py

from django.db import models
from employee.models import Employee

# Create your models here.

class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    date = models.DateField()
    day = models.CharField(max_length=10)
    in_time = models.CharField(max_length=5)
    out_time = models.CharField(max_length=5)

这是我的views.py

from django.shortcuts import render,redirect
from django.views.generic import View
from django.http import JsonResponse
from employee.models import Employee
from .models import Attendance

# Create your views here.

class MarkAttendanceMainView(View):
    def get(self,request):
        return render(request,"mark_attendance.html")
    def post(self,request):
        attendance_time_in =  []
        attendance_time_out = []
        attendance_date = []
        attendance_day = []
        emp_id = request.POST['attendance_emp_id']
        emp = Employee.objects.filter(emp_id=emp_id)
        for id in request.POST:
            if "in" in id.split("_"):
                attendance_time_in.append(id)
            elif "out" in id.split("_"):
                attendance_time_out.append(id)
            elif "date" in id.split("_"):
                attendance_date.append(id)
            elif "day" in id.split("_"):
                attendance_day.append(id)
        i = 0
        while i < len(attendance_time_in):
            date = request.POST[attendance_date[i]]
            day = request.POST[attendance_day[i]]
            time_in = request.POST[attendance_time_in[i]]
            time_out = request.POST[attendance_time_out[i]]
            i +=1
            print(emp, date, day, time_in, time_out)
            attendance = Attendance(emp,date,day,time_in,time_out)
            attendance.save()

        return redirect('mark_attendance_main_view')

错误回溯

File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\hrms\attendance\views.py", line 37, in post
    attendance.save()
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\base.py", line 739, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\base.py", line 776, in save_base
    updated = self._save_table(
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\base.py", line 858, in _save_table
    updated = self._do_update(base_qs, using, pk_val, values, update_fields,
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\base.py", line 912, in _do_update
    return filtered._update(values) > 0
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\query.py", line 802, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\sql\compiler.py", line 1559, in execute_sql
    cursor = super().execute_sql(result_type)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\sql\compiler.py", line 1162, in execute_sql
    sql, params = self.as_sql()
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\sql\compiler.py", line 1525, in as_sql
    val = field.get_db_prep_save(val, connection=self.connection)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\fields\__init__.py", line 1271, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\fields\__init__.py", line 1266, in get_prep_value
    return self.to_python(value)
  File "C:\Users\D e L L\Desktop\Chamika\Python\HRMS\hrms\Lib\site-packages\django\db\models\fields\__init__.py", line 1238, in to_python
    raise exceptions.ValidationError(

Exception Type: ValidationError at /attendance/mark_attendance
Exception Value: ['“Sunday” value has an invalid date format. It must be in YYYY-MM-DD format.']

html模板

{% extends "base.html" %}
{% load static %}

{% block title %} Mark Attendance {% endblock%}

{% block top_heading %}Attendance Management{% endblock %} {% block sub_heading %}/ Mark Attendance{% endblock %}

{% block content %}
<form method="POST">
    {% csrf_token %}
<div class="card formss">
    <div class="card-body row g-3">

            <div class="col-md-2">
                <label class="col-form-label" for="attendance_emp_id">Employee ID</label>
                <div class="">
                    <input data-url="{% url 'get_emp_name_view' %}" class="form-control" type="text" name="attendance_emp_id" id="attendance_emp_id" required>
                </div>

            </div>

            <div class="col-md-6">
                <label class=" col-form-label" for="attendance_emp_name">Name</label>
                <div class="">
                    <input class="form-control" type="text" name="attendance_emp_name" id="attendance_emp_name" disabled required>
                </div>
            </div>

            <div class="col-md-4">
                <label class=" col-form-label" for="attendance_month_year">Month/Year</label>
                <div class="">
                    <input onchange="getYearMonth();" class="form-control" type="month" name="attendance_month_year" id="attendance_month_year">
                </div>
            </div>
    </div>
</div>

<div class="card formss">
    <div class="card-body row g-3 " id="attendance_dates_div">
        
        <div class="col-md-3">
            <label class="col-form-label" for="attendance_date">Date</label>
        </div>
        
        <div class="col-md-3">
            <label class=" col-form-label" for="attendance_day">Day</label>
        </div>
        
        <div class="col-md-2">
            <label class=" col-form-label" for="attendance_month_date">Time In</label>
        </div>
        <div class="col-md-2">
            <label class=" col-form-label" for="attendance_month_date">Time Out</label>
        </div>
    </div>
</div>
</form>

<script >
    console.log("Workingggg");
    //Get employee name
    var attendance_emp_id_input = document.getElementById("attendance_emp_id");
    var attendance_emp_name_input = document.getElementById("attendance_emp_name");
    attendance_emp_id_input.addEventListener("keypress", function (event) {
        if (event.key === "Enter") {
            event.preventDefault();
            attendance_emp_name_input.value = "";
            attendance_emp_id = attendance_emp_id_input.value;

            $.ajax({
                type:'POST',
                url: "{% url 'get_emp_name_view' %}",
                data: {
                    name : attendance_emp_id,
                    csrfmiddlewaretoken :$('input[name=csrfmiddlewaretoken]').val(),
                },
                success: function (response) {
                    console.log("Done")
                    console.log(response.name)
                    attendance_emp_name_input.value = response.name
                }
            });
        }
    });

    //Get Dates according to the month
    function getYearMonth() {
        var attendance_month_year_select = document.getElementById("attendance_month_year");
        var attendance_month_date = attendance_month_year_select.value;
        var attendance_month_date_split = attendance_month_date.split('-');
        var attendance_year = attendance_month_date_split[0];
        var attendance_month = attendance_month_date_split[1];
        var attendance_set_date = attendance_year + "-" + attendance_month + "-01"

        var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        var i = 1;
        const date = new Date(attendance_year, attendance_month - 1, i);
        var dates = [];
        $("#attendance_dates_div").empty()
        $("#attendance_dates_div").append('<div class="col-md-3"><label class= "col-form-label" for= "attendance_date" > Date</label ></div ><div class="col-md-3"><label class=" col-form-label" >Day</label></div><div class="col-md-2"><label class=" col-form-label" >Time In</label></div><div class="col-md-2"><label class=" col-form-label">Time Out</label></div>')
        while (date.getMonth() === (parseInt(attendance_month) - 1)) {
            dates.push(new Date(date));
            
            $("#attendance_dates_div").append('<div class="col-md-3"><div class=""><input  class="form-control" readonly type="date" name="attendance_date_' + i +'" id="attendance_date_'+ i +'"></div></div ><div class="col-md-3"><div class=""><input class="form-control" type="text" name="attendance_day_' + i +'" id="attendance_day_' + i +'" readonly></div></div><div class="col-md-2"><div class=""><input  class="form-control" type="text" name="attendance_time_in_' + i +'"id="attendance_time_in_' + i +'""></div></div><div class="col-md-2"><div class=""><input  class="form-control" type="text" name="attendance_time_out_' + i +'""id="attendance_time_out_' + i +'""></div></div>')
            
            var attendance_date_random = "attendance_date_"+ i;
            var attendance_day_random = "attendance_day_" + i;
            document.getElementById(attendance_date_random).defaultValue = attendance_year + "-" + attendance_month + "-" + (i < 10 ? ("0"+ i): i) ;
            var dayName = days[date.getDay()];
            document.getElementById(attendance_day_random).value = dayName ;
            date.setDate(date.getDate() + 1);
            i = i + 1
        }
        $("#attendance_dates_div").append('<div class="text-center"><button class= "btn btn-primary" > Submit Data</button ></div > ')
        
    }
    function getAllDaysInMonth(year, month) {
        const date = new Date(year, month, 1);

        const dates = [];

        while (date.getMonth() === month) {
            dates.push(new Date(date));
            date.setDate(date.getDate() + 1);
        }

        return dates;
    }

</script>

{% endblock %}
``

Here are some of post data

attendance_emp_id   
'A65465'
attendance_month_year   
'2023-01'
attendance_date_1   
'2023-01-01'
attendance_day_1    
'Sunday'
attendance_time_in_1    
'10.00'
attendance_time_out_1   
'23.00'
attendance_date_2   
'2023-01-02'
attendance_day_2    
'Monday'
attendance_time_in_2    
'15.00'
attendance_time_out_2   
'12.00'
3zwjbxry

3zwjbxry1#

这里我没有指定主键,Django已经自动创建了一个,所以当保存Attendance模型时idAttendance(id, employee, ...)之前
因此,我必须特别提到Attendance(employee=emp, date=date, day=day, ...)这样的字段

相关问题