views.py
def create_employee(request):
if not request.user.is_authenticated():
return render(request, 'blazon/login.html')
else:
form = EmployeeForm(request.POST or None, request.FILES or None)
if form.is_valid():
employee = form.save(commit=False)
context = {
'employee': employee,
'form': form,
}
employee.save()
return render(request, 'blazon/create_employee.html', context)
return render(request, 'blazon/employees.html', {'employee': employee})
return render(request, 'blazon/create_employee.html', {"form": form,})
urls.py
url(r'^create_employee/$', views.create_employee, name='create_employee'),
这是我在项目中创建新员工的视图功能。表单被呈现,当我点击提交时,对象被填充到数据库中,但它不会被重定向到employees.html页面。
我尝试过但没有运气!
return redirect('blazon:employees)
而不是上面的渲染功能。我如何重定向到employees.html页面? TIA
答案 0 :(得分:2)
您希望在此视图上点击create_employee.html
请求时呈现GET
。但是,当您使用POST
请求点击视图时,应该执行您在此处发布的整个if-else块(最后一行除外)。
您应该做出一些改变:
if not request.user.is_authenticated():
return render(request, 'blazon/login.html')
之后不需要这样做,因为如果用户未经过身份验证,则会在页面上方呈现。控制退出此功能。请注意以下几行。
接下来,
form = EmployeeForm(request.POST or None, request.FILES or None)
if form.is_valid():
employee = form.save(commit=False)
context = {
'employee': employee,
'form': form,
}
employee.save()
return render(request, 'blazon/employees.html', {'employee': employee})
这不应包含return render(request, 'blazon/create_employee.html', context)
,因为这是您在GET
请求时要执行的操作。
接下来,您走出POST
方法处理块,然后渲染所需的页面。
return render(request, 'blazon/create_employee.html', {"form": form,})
答案 1 :(得分:0)
if request.user.is_authenticated(): #checking if user is authnticated
if request.method == 'POST':
form = EmployeeForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
return redirect('blazon:employees') #redirecting after saving the form
else:
form = EmployeeForm() #if request is get empty form
return render(request, 'blazon/create_employee.html', {"form": form,})
答案 2 :(得分:0)
您的employees.html
重定向无法访问,因为您上面有另一个return
。只需删除它。改变这个:
return render(request, 'blazon/create_employee.html', context)
return render(request, 'blazon/employees.html', {'employee': employee})
到此:
# return render(request, 'blazon/create_employee.html', context)
return render(request, 'blazon/employees.html', {'employee': employee})