def add_employee_old(request): if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") dep = request.POST.get("dep") info = request.POST.get("info") salary = request.POST.get("salary") # Get multiple values groups = request.POST.getlist("group") new_emp = employee.objects.create(name = name,email = email,salary = salary,dep_id = dep,info_id = info) # Assign values to many to many key fields new_emp.group.set(groups) return redirect('/test_orm_old/list_employee_old/') dep_list = department.objects.all() group_list = group.objects.all() info_list = employeeinfo.objects.all() return render(request,'test_orm_old/add_employee_old.html',{
'dep_list':dep_list,'group_list':group_list,'info_list':info_list})
add_employee_old.html Code :
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title> increase </title> </head> <body> <div align="center"> <h1> Increase staff </h1> <hr> <form action="/test_orm_old/add_employee_old/" method="post"> {% csrf_token %} <div> <label> full name :</label><input type="text" name="name" id="name"> </div> <br> <div> <label> mailbox :</label><input type="text" name="email" id="email"> </div> <br> <div> <label> salary :</label><input type="text" name="salary" id="salary"> </div> <br> <div> <label> Contact information :</label> <select name="info" id="info"> {% for info in info_list %} <option value="{
{ info.id }}">{
{ info.phone }}||{
{ info.address }}</option> {% endfor %} </select> </div> <br> <div> <label> department :</label> <select name="dep" id="dep"> {% for dep in dep_list %} <option value="{
{ dep.id }}">{
{ dep.dep_name }}</option> {% endfor %} </select> </div> <br> <div> <label> group :</label> <!-- Field group It's many to many , Set up <select> Tag attributes multiple="true", Allow multiple selection --> <select name="group" id="group" multiple="true"> {% for group in group_list %} <option value="{
{ group.id }}">{
{ group.group_name }}</option> {% endfor %} </select> </div> <br> <div><input type="submit" value=" increase "></div> </form> </div> </body></html>
Click Save to report the following error :
IntegrityError at /test_orm_old/add_employee_old/
(1062, "Duplicate entry '4' for key 'employee_employee.info_id'")
Request Method: POST
1062, "Duplicate entry '4' for key 'employee_employee.info_id'" The primary key is repeated l You type 5 Try reading the error no