Trying to create an update function for a Department Model in Django but i’ve run into a problem. Here’s what i have so far
update view function
def department(request):
data = main_collection.objects.all()
filtered_data = []
for datas in data:
if datas.user_type.user_type in ['admin', 'employee']:
filtered_entry = {
'user_type': datas.user_type.user_type,
'role': datas.user_type.user_type,
'employee_first_name': datas.employee.first_name,
'organization_name': datas.organization.org_name,
'organization_id': datas.organization.id,
'department_name': datas.department.department_name,
'employee_id': datas.employee.id,
'department_id':datas.department.id,
}
filtered_data.append(filtered_entry)
# remove duplicated departmant name
unique_department = {entry['department_name'] for entry in filtered_data}
filtered_data_unique =[]
for entry in filtered_data:
if entry['department_name'] in unique_department:
filtered_data_unique.append(entry)
unique_department.remove(entry['department_name'])
manager_data = [entry for entry in filtered_data if entry['user_type'] == 'admin']
return render(request, 'department/homee.html', {'data': filtered_data, 'manager':manager_data})
def add_view(request):
#print("Reached add_view function----------------------------------------------------------------------------------------------------------------------------------------------------------------------")
if not request.user.is_authenticated:
messages.error(request, 'You are not logged in')
return redirect('department_app:department')
try:
#print("Reached add_view function 22222222----------------------------------------------------------------------------------------------------------------------------------------------------------------------")
if request.method == "POST":
dep_name = request.POST.get('dep_name')
organization_id = request.POST.get('organization_id')
employee_name = request.POST.get('emp_first_name')
org_name = request.POST.get('orga_name')
employee_id = request.POST.get('employee_id')
if dep_name and organization_id and employee_id:
organization = get_object_or_404(Organization, pk=organization_id)
employee = get_object_or_404(Employee, pk=employee_id)
# Check if there's any department with NULL department_name for the given organization
department = Department.objects.filter(department_name__isnull=True, organization=organization).first()
if department:
# If a department with NULL name exists, update it
department.department_name = dep_name
department.manager = employee
department.save() # Save the updated department
#print(f"Updated department '{dep_name}' with Employee ID: {employee_id} and Organization ID: {organization_id}")
messages.success(request, "Department Added Successfully!!!!!")
return redirect('department_app:department')
# Debug output
#print(f"'{department.id}', '{department.department_name}', '{datetime.now()}', '{organization_id}', '{employee_id}'")
else:
messages.error(request, f"Employee already exists with Department:{dep_name}")
#print(f"Employee already exisite a Department'{dep_name}' with Employee ID: {employee_id} and Organization ID: {organization_id}")
# If no NULL department exists, create a new one
"""department = Department.objects.create(
department_name=dep_name,
organization=organization,
manager=employee"""
# Main collection entry is created after department is updated or created
main_collection_entry = main_collection.objects.create(
department=department
)
# Debug print statement to confirm main_collection entry creation
#print(f"main_collection entry created with ID: {main_collection_entry.id}")
#print(f"'{main_collection_entry.id}', NULL, '{datetime.now()}', '{organization_id}', '{employee_id}'")
#messages.success(request, 'Your department has been added or updated')
return redirect('department_app:department')
else:
messages.error(request, 'Department name, organization ID, or employee first name is missing.')
return redirect('department_app:add_view')
return render(request, 'department/add.html')
except Exception as e:
messages.error(request, f'Error occurred: {str(e)}')
return redirect('department_app:department')
def update_view(request, department_id):
# Fetch the department using the ID
try:
department =main_collection.objects.get(id=department_id)
if request.method =='POST':
department_name = request.POST.get('dep_name')
department.save()
except Department.DoesNotExist:
department = None
# Pass the department data to the template
return render(request, 'department/update.html', {'department': department})
i am calling the function to collecting department id from here
update.html
this is my
add_user.html
this line setting department id to edit
<a class="btn-edit-contact" data-id="{{ datas.department_id }}" data-bs-toggle="modal" data-bs-target="#upp">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-2 edit">
<path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path>
</svg>
</a>
urls.py
from django.urls import path
from apps.Department.views import department, add_view, update_view
app_name = "department_app"
urlpatterns = [
path('department/', department, name='department'),
path('add_view/', add_view, name='add_view'),
path("update_view/<int:department_id>/", update_view, name="update_view"),
]
Error during template rendering
In template C:\Users\JULIAN\Desktop\hr-system-gen1\apps\Department\templates\department\add_user.html, error at line 3
Reverse for 'update_view' with no arguments not found. 1 pattern(s) tried: ['update_view/(?P<department_id>[0-9]+)/\\Z']
1 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
2
3 <form method="POST" action="{% url 'department_app:update_view' %}" enctype="multipart/form-data">