我对django很新。我完成了django项目教程,并且很好地理解了它,至少我以为我做到了。我对urls.py和views.py如何相关的理解是urls.py指向views.py的功能,并根据页面查找要执行的文件。
这是我的文件结构:
根文件夹位于名为“ff”
的“friendfinder”文件夹的正上方我在所有3个静态html页面上显示的404错误:索引,朋友和联系人。
以下是我的urls.py页面:
from django.conf.urls import url
from gather import views
urlpatterns = [
url(r'^interest/', views.InterestView.as_view(), name="interest"),
url(r'^$', views.index, name="index"),
url(r'^friends/', views.friends, name="friend"),
url(r'^contact/', views.contact, name="contact"),
]
这是我的views.py页面:
import json
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from gather.models import Interest
def index(request):
all_interests = Interest.objects.all()
return render(
request,
' gather/index.html',
{
'stuff': 'TEST',
'interests': all_interests
}
)
def friends(request):
return render(request, 'gather/friends.html')
def contact(request):
return render(request, 'gather/contact.html')
class InterestView(View):
def post(self, request):
try:
json_data = json.loads(request.body.decode('utf-8'))
new_interest = Interest(
name=json_data['name'],
description=json_data['description'],
approved=False
)
new_interest.save()
return HttpResponse('ok')
except ValueError:
return HttpResponse('Fail', status=400)
def get(self, request):
try:
search = request.GET.get("search", None)
interests = Interest.objects.filter(name__icontains=search)
interest_json = []
for interest in interests:
interest_json.append({
'name': interest.name,
'description': interest.description
})
return JsonResponse({'search_result': interest_json})
except ValueError:
return HttpResponse('404 Page Not Found', status=400)
在我安装了应用程序的settings.py页面上,我添加了名为“gather”的应用程序和
ROOT_URLCONF = friendfinder.urls
我还看了一下这页:urls.py and views.py information
我想也许我的问题是文件结构问题。 任何指针,提示,技巧和/或解释为什么urls.py和views.py页面彼此不匹配的信息将不胜感激。
编辑:Friendfinder的代码/ urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('gather.urls', namespace='gather', app_name='gather'))
]