My code does not work.

Hello! I’ve started my first project in Django. I have to log in as an manager and add employees and tasks. I created 2 html files for my forms and i’ve also created my models.py file. This is my models.py file.

from django.contrib.auth.models import AbstractUser
from django.db import models
from tkinter import CASCADE
from django.dispatch import receiver
from django.db.models.signals import post_save
# Create your models here.

class CustomUser(AbstractUser):
    user_type_data = ((1,"Manager"),(2,"Employee"))
    user_type = models.CharField(default = 'test', choices = user_type_data, max_length=20)
    name = models.CharField(max_length = 100,default='test')
    email = models.CharField(max_length = 100,default='test')
    password = models.CharField(max_length = 100,default='test')

class Manager(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now_add = True)
    objects = models.Manager()
    
class Tasks(models.Model):
    id = models.AutoField(primary_key=True)
    headline = models.CharField(max_length = 100)
    body = models.CharField(max_length = 10000)
    created_at = models.DateTimeField(auto_now_add = True)
    assigned_at =  models.DateTimeField(auto_now_add = True)
    closed_at =  models.DateTimeField(auto_now_add = True)
    manager_id = models.ForeignKey(Manager, on_delete=models.CASCADE)
    objects = models.Manager()


class Employee(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    #name = models.CharField(max_length = 100,default='test')
    #email = models.CharField(max_length = 100,default='test')
    #password = models.CharField(max_length = 100,default='test')
    objects = models.Manager()
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now_add = True)
    tasks_id = models.ForeignKey(Tasks, on_delete=models.CASCADE)
    daily_r = models.IntegerField(default = 0)
    weekly_r = models.IntegerField(default = 0)
    monthly_r = models.IntegerField(default = 0)
    annual_r = models.IntegerField(default = 0)


@receiver(post_save, sender = CustomUser)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        if instance.user_type ==1:
            Manager.objects.create(admin=instance)
        if instance.user_type ==2:
            Employee.objects.create(admin=instance, daily_r ="",weekly_r="",monthly_r="",annual_r="")

@receiver(post_save, sender = CustomUser)
def save_user_profile(sender, instance, created, **kwargs):
    if instance.user_type ==1:
        instance.manager.save()
    if instance.user_type ==2:
        instance.employee.save()

I have a managerview.py file where I created 2 functions that helps me add employees and tasks.

def addTask(request):
    employee = Employee.objects.filter(user_type = 2)
    return render(request,"add_task.html",{"employees": employee})

def addTaskSave(request):
    if request.method!="POST":
        return HTTPResponse("Method Not Allowed")
    else:
        headline=request.POST.get("headline")
        body=request.POST.get("body")
        try:
            task_model=Tasks(headline=headline, body = body)
            task_model.save()
            return HttpResponseRedirect(reverse("add_task"))
        except:
            return HttpResponseRedirect(reverse("add_task"))
            
def addEmployee(request):
    return render(request, "add_employee.html")

def addEmployeeSave(request):
    if request.method != 'POST':
        return HTTPResponse("Method Not Allowed")
    else:
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        try:
            user = CustomUser.objects.create_user(first_name = first_name, last_name=last_name, username = username, email = email, password = password,  user_type = 2)
            tasks_obj=Courses.objects.get(id=tasks_id)
            user.employee.tasks_id = tasks_obj
            user.save()
            messages.success(request, "Employee added successfully!")
            return HttpResponseRedirect(reverse("/addEmployee"))
        except:
            return HttpResponseRedirect("/addEmployee")

The problem is I can’t add any employees or tasks and I have no errors. What did I do wrong in my project and what can I change to make it work?

Your program structure shows a distinct non-Django-style pattern here.

Have you worked your way through either of the Official Django Tutorial or the Django Girls Tutorial?

If not, I suggest you do so to learn the generally accepted patterns and to perhaps get a better understanding of how Django works.

We’re also going to need to see the templates involved here.

You may also want to review the Working with forms page, particularly the section for The view.

(I’ll also point out that I consider it unwise to use signals in cases where they’re not absolutely necessary. If you browse the messages on this board, you’ll find multiple threads discussing them.)

1 Like

I read the django documentation and followed simple Django tutorials, after which I tried to do some easy projects on my own. This is my add_employee.html file which contains the form.

<form action ="addEmployeeSave" method = "POST">
                                {%csrf_token%}
                                <div class="card-body">
                                    <h4 class="card-title">Personal Info</h4>
                                    <div class="form-group row">
                                        <label for="fname" class="col-sm-3 text-right control-label col-form-label">First Name</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" id="first_name" placeholder="First Name Here" name ="first_name">
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="lname" class="col-sm-3 text-right control-label col-form-label">Last Name</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" id="last_name" placeholder="Last Name Here" name ="last_name">
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="username" class="col-sm-3 text-right control-label col-form-label">Username</label>
                                        <div class="col-sm-9">
                                            <input type="text" class="form-control" id="username" placeholder="Username Here" name ="username">
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="email" class="col-sm-3 text-right control-label col-form-label">Email</label>
                                        <div class="col-sm-9">
                                            <input type="email" class="form-control" id="email" placeholder="Email Here" name ="email">
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="password" class="col-sm-3 text-right control-label col-form-label">Password</label>
                                        <div class="col-sm-9">
                                            <input type="password" class="form-control" id="password" placeholder="Password Here" name ="password">
                                        </div>
                                    </div>
                                    
                                </div>
                                <div class="border-top">
                                    <div class="card-body">
                                        <button type="button" class="btn btn-primary">Submit</button>
                                    </div>
                                </div>
                            </form>

You are not rendering a form here. You are manually defining individual HTML elements.

If you have not actually worked your way through either of the Django tutorials referenced above, I suggest you do so. (Not just read them - type the code and the examples as appropriate.)

You also should read the entire Working with forms page in the docs.

1 Like