由于某些url配置问题,我觉得服务器无法很好地呈现视图。它总是呈现消息Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/emp
这是我的项目结构
|--hrdjango
|--employee
|--migrations folder
|--admin.py
|--urls.py
...
|views.py
|--hrdjango
...
|--settings.py
|--urls.py
views.py
from django.shortcuts import render, redirect
from .forms import EmployeeForm
from .models import Employee
# Create your views here.
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
employee = Employee.objects.get(id=id)
employee.delete()
return redirect("/show")
employee / urls.py
from .import views
from django.contrib import admin
from django.urls import path, include
app_name = 'employee'
urlpatterns = [
path('', views.emp, name='emp'),
path('show',views.show, name='show'),
path('edit/<int:id>', views.edit, name='edit'),
path('update/<int:id>', views.update, name='update'),
path('delete/<int:id>', views.destroy, name='destroy'),
]
hrdjango /网址
from django.contrib import admin
from django.urls import include, path
from employee import views
urlpatterns = [
path('admin/', admin.site.urls),
path('employee/', include('employee.urls')),
path('', views.emp),
]
我希望看到根据我的urls配置渲染的视图,但是似乎无法渲染我的视图,因为它没有看到它。
答案 0 :(得分:0)
您没有使用此网址格式为http://127.0.0.1:8000/emp
的任何url,而是尝试了例如:
http://127.0.0.1:8000/
http://127.0.0.1:8000/show
或 employee / urls.py
中定义的其他URL答案 1 :(得分:0)
如果要访问emp(request)
视图。
from django.contrib import admin
from django.urls import include, path
from employee import views
urlpatterns = [
path('admin/', admin.site.urls),
path('employee/', include('employee.urls')),
# path('', views.emp), - remove this line
]
然后,例如,您可以发出GET
这样的请求。
emp(request)
方法此外,在您的ModelForm
Meta
类中,您应该指定Employee
类而不是Employee
类实例。
from django import forms
from .models import Employee
class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = '__all__'
希望对您有帮助。