Home > Back-end >  I have created models and my views function to add the attendance of employee. But data is not savin
I have created models and my views function to add the attendance of employee. But data is not savin

Time:10-27

I have created a form named as AttendanceForm :

class AttendanceForm(forms.ModelForm):
    class Meta:
        model = Attendance
        fields = '__all__'

These are models

class Employee(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    eid = models.IntegerField(primary_key=True)
    salary = models.IntegerField()
    gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1)
    contactno = models.CharField(max_length=10)
    email = models.CharField(max_length=30)
    country = models.CharField(max_length=30)
    city = models.CharField(max_length=20)
    pincode = models.IntegerField()
    address = models.CharField(max_length=60)

    def __str__(self):
        return self.user.first_name   ' '   self.user.last_name


class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1)
    attendancedate = models.DateField()
    in_time = models.TimeField()
    out_time = models.TimeField()
    description = models.TextField()

    def __str__(self):
        return str(self.employee)

view for attendance.

@csrf_exempt
def addattendance(request):
    form = AttendanceForm()
    emp_list = Employee.objects.all()
    if request.method == 'POST':
        form = AttendanceForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return redirect('employee/detail_attendance')

    return render(request, 'employee/addattendance.html', {'form': form, 'emp_list': emp_list})

I tried everything, but I don't know why the data is not saving into the database. Also, models are created fine, and the main thing is that there are no errors coming up.  Please let me know if any changes are required.

CodePudding user response:

I can suggest simple solution with Class-Based-Views:

from django.views.generic.edit import FormView

def AddAttendanceFormView(FormView):
    form_class = AttendanceForm
    extra_context = {"emp_list": Employee.objects.all()}
    success_url = reverse_lazy('employee/detail_attendance')
    template_name = 'employee/addattendance.html'

    def post(self, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        return self.form_invalid(form)

Remember, that in urls.py you need to use .as_view() for class based views, like:

path((...), AddAttendanceFormView.as_view())

Also, you will not need @csrf_exempt, just put {% csrf_token %} anywhere inside your form's template.

CodePudding user response:

Here i changed some things please check it...

in models.py

GENDER_CHOICES = (('Male','Male'),('Female','Female'))
class Employee(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    eid = models.IntegerField(primary_key=True)
    salary = models.IntegerField()
    gender = models.CharField(max_length=6, choices=GENDER_CHOICES)
    contactno = models.CharField(max_length=10)
    email = models.CharField(max_length=30)
    country = models.CharField(max_length=30)
    city = models.CharField(max_length=20)
    pincode = models.IntegerField()
    address = models.CharField(max_length=60)

    def __str__(self):
        return self.user.first_name   ' '   self.user.last_name

class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1)
    attendancedate = models.DateField()
    in_time = models.TimeField()
    out_time = models.TimeField()
    description = models.TextField()

    def __str__(self):
        return str(self.employee)

in form.py

from django import forms
from .models import *

class AttendanceForm(forms.ModelForm):
    class Meta:
        model = Attendance
        fields = '__all__'
        widgets= {

            'attendancedate':forms.TextInput(attrs={'type':'date'}),
            'in_time':forms.TextInput(attrs={'type':'time'}),
            'out_time':forms.TextInput(attrs={'type':'time'}),
        }

in views.py

from django.shortcuts import render, redirect
from .models import *
from .form import *


def addattendance(request):
    form = AttendanceForm()
    emp_list = Employee.objects.all()
    if request.method == 'POST':
        form = AttendanceForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return redirect('employee/detail_attendance')

    return render(request, 'index.html', {'form': form, 'emp_list': emp_list}) 

in HTML

{% block body %}
     <form action="" method="POST">
          {% csrf_token %}
          {{form.as_p}}
          <button type="submit">add</button>
     </form>

{% endblock body %}

Attendance Form

enter image description here

  • Related