am going to give my code for my model my view and frontend that i want to use for task creation and prioritization.
I want to look at them carefully and give me proper working updated codes . i what to be able to create a task and add to my database then the staff member can be able to view the tasks and see their priority. there is a model responsible for task prioritization.
following are the code in python django:
class Task(models.Model):
PRIORITY_CHOICES = [
(“Critical”, “Critical”),
(“High”, “High”),
(“Medium”, “Medium”),
(“Low”, “Low”),
]
STATUS_CHOICES = [
("Pending", "Pending"),
("In Progress", "In Progress"),
("Completed", "Completed"),
]
project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='tasks', null=True, blank=True)
name = models.CharField(max_length=255, help_text="Name of the task")
description = models.TextField(blank=True, help_text="Detailed description of the task")
assigned_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
progress = models.IntegerField(default=0)
due_date = models.DateField(null=True, blank=True)
estimated_duration = models.FloatField(help_text="Estimated time (in hours) to complete the task")
priority = models.CharField(max_length=20, choices=PRIORITY_CHOICES, blank=True, null=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='Pending')
dependencies = models.ManyToManyField("self", blank=True, symmetrical=False)
created_at = models.DateTimeField(default=now, auto_now_add=False) # Use default=now instead of auto_now_add=True
updated_at = models.DateTimeField(auto_now=True)
priority_score = models.IntegerField(default=0, editable=False) # Store the calculated priority score
def calculate_priority_score(self):
score = 0
# Add points based on priority level
if self.priority == 'Critical':
score += 100
elif self.priority == 'High':
score += 75
elif self.priority == 'Medium':
score += 50
elif self.priority == 'Low':
score += 25
# Add points based on days remaining
if self.due_date:
if isinstance(self.due_date, str):
self.due_date = datetime.strptime(self.due_date, "%Y-%m-%d").date() # Convert to date
days_remaining = (self.due_date - now().date()).days
if days_remaining <= 3:
score += 50
elif days_remaining <= 7:
score += 25
# Add points based on dependencies
score += 10 * self.dependencies.count()
# Update the priority score
self.priority_score = score
return score
def save(self, *args, **kwargs):
# Automatically calculate priority score before saving
self.calculate_priority_score()
super().save(*args, **kwargs)
def __str__(self):
return f"Task {self.id} - {self.priority}"
@login_required
def create_task(request, project_id):
if request.method == ‘POST’:
try:
# Get the project
project = get_object_or_404(Project, id=project_id, created_by=request.user)
# Extract form data
name = request.POST.get("name")
description = request.POST.get("description", "")
dependencies = int(request.POST.get("dependencies", 0))
status = request.POST.get("status")
estimated_duration = float(request.POST.get("estimated_duration", 0))
assigned_to_id = request.POST.get("assigned_to")
# Validate required fields
if not name or not status or estimated_duration <= 0:
return JsonResponse({'error': 'Invalid input data'}, status=400)
# Load model & predict priority
base_dir = os.path.dirname(os.path.abspath(__file__))
model_path = os.path.join(base_dir, "static", "my_app", "ml_model", "construction_prioritization_model.joblib")
model = joblib.load(model_path)
input_data = pd.DataFrame([{
"Dependencies": dependencies,
"Status": status,
"Estimated Duration": estimated_duration,
}])
predicted_priority = model.predict(input_data)[0]
# Fetch the assigned user
assigned_to = User.objects.get(id=assigned_to_id) if assigned_to_id else None
# Create the task
task = Task.objects.create(
project=project,
name=name,
description=description,
dependencies=dependencies,
status=status,
estimated_duration=estimated_duration,
priority=predicted_priority,
assigned_to=assigned_to,
)
# Return success response
return JsonResponse({'message': 'Task created successfully'})
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
Create New Task
× <div class="form-group">
<label for="description">Description:</label>
<textarea name="description" id="description" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="dependencies">Dependencies:</label>
<input type="number" name="dependencies" id="dependencies" class="form-control" required>
</div>
<div class="form-group">
<label for="status">Status:</label>
<select name="status" id="status" class="form-control" required>
<option value="Pending">Pending</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>
</div>
<div class="form-group">
<label for="estimatedDuration">Estimated Duration (hrs):</label>
<input type="number" step="0.1" name="estimated_duration" id="estimatedDuration" class="form-control" required>
</div>
<div class="form-group">
<label for="assignedTo">Assign To:</label>
<select name="assigned_to" id="assignedTo" class="form-control">
<option value="" disabled selected>Select a staff member</option>
{% for staff in staff_members %}
<option value="{{ staff.id }}">{{ staff.first_name }} {{ staff.last_name }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">Create Task</button>
</form>
<script>
document.getElementById("createTaskForm").addEventListener("submit", async function (e) {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
const response = await fetch("{% url 'create_task' project.id %}", {
method: "POST",
headers: {
"X-CSRFToken": formData.get("csrfmiddlewaretoken"),
},
body: formData,
});
const result = await response.json();
alert(result.message || "Task created");
closeModal();
location.reload();
});
</script>
</div>
i want these to communicate with each other well for me to achieve proper functionality