我有一个django应用,但是我想制作它的API,所以我就创建了它 运行服务器后
找不到页面(404)
但是我的django应用正在运行,在运行API的网址后,我收到页面未找到的错误
List / views.py
from django.http import Http404
from django.shortcuts import render
from django.views.generic import ListView,DetailView
from .models import List
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from List.serializers import ListSerializers
class MainListView(ListView):
queryset = List.objects.all()
# temp = List.objects.all()
template_name = "main_list.html"
def get_context_data(self, *args, **kwargs):
context = super(MainListView, self).get_context_data(*args, **kwargs)
context['temp'] = List.objects.all()
return context
class MainListView(ListView):
queryset = List.objects.all()
# temp = List.objects.all()
template_name = "List/list.html"
def get_context_data(self, *args, **kwargs):
context = super(MainListView, self).get_context_data(*args, **kwargs)
context['temp'] = List.objects.all()
return context
class MainDetailSlugView(DetailView):
queryset = List.objects.all()
template_name = "news/detail.html"
@csrf_exempt
def head_list(request):
if request.method == 'GET':
queryset = List.objects.all()
serializer = ListSerializer(queryset, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = ListSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def head_detail(request, pk):
try:
head = List.objects.get(pk=pk)
except List.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = ListSerializer(list)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(head, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
head.delete()
return HttpResponse(status=204)
List / urls.py
from django.urls import path
from List import views
from .views import(
# ListlistView,
MainListView,
MainDetailSlugView,
head_list,
head_detail
)
urlpatterns = [
# url(r'^$',ListlistView.as_view()),
path('',MainListView.as_view(),name='list'),
path('(<pk>\d+)(?:/(<slug>[\w\d-]+))',MainDetailSlugView.as_view(), name='List'),
path('list/',views.list_list),
path('lists/<int:pk>/',views.list_detail),
]
List / serializers.py
from rest_framework import serializers
from List.models import List
class ListSerializers(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=True, allow_blank=False,max_length=120)
slug = serializers.SlugField(required=False,)
description= serializers.CharField(required=True, allow_blank=False)
image = serializers.ImageField(required=True,)
timestamp = serializers.DateTimeField(required=True,)
code = serializers.CharField(style={'base_template': 'textarea.html'})
language = serializers.CharField(default='python')
style = serializers.CharField(default='friendly')
def create(self, validated_data):
return List.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.descritption = validated_data.get('descritption', instance.descritption)
instance.image = validated_data.get('image', instance.image)
instance.timestamp = validated_data.get('timestamp',instance.timestamp)
instance.language = validated_data.get('language',instance.language)
instance.style = validated_data.get('style',)
instance.save()
return instance
List / models.py
import random
import os
from django.db import models
from django.urls import reverse
from django.db.models.signals import pre_save, post_save
from lokswar.utils import unique_slug_generator
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0],item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item,item) for item in get_all_styles())
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name,ext
def upload_image_path(instence, filename):
new_filename = random.randint(1,396548799)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext= ext)
return "card/{new_filename}/{final_filename}".format(new_filename=new_filename,
final_filename=final_filename)
class ListQuerySet(models.query.QuerySet):
def active(self):
return self.filter(active=True)
class ListManager(models.Manager):
def get_queryset(self):
return ListQuerySet(self.model, using=self._db)
def all(self):
return self.get_queryset().active()
class List(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
description= models.TextField()
image = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
code = models.TextField(default=True)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
objects = ListManager()
class Meta:
ordering = ('created',)
def get_absolute_url(self):
return reverse('List', kwargs={'pk': self.pk, 'slug': self.slug })
def __str__(self):
return self.title
def __unicode__(self):
return self.title
请帮助我解决此错误。
我试图通过此URL http://127.0.0.1:8000/List/list/
urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from .views import HomeListView
urlpatterns = [
path('List',include('List.urls'), name="List"),
path('news/',include('news.urls'), name="news"),
path('', HomeListView.as_view(), name='home'),
path('sports/',include('sports.urls'), name="sports"),
path('movie/',include('movie.urls'), name="movie"),
path('business/',include('business.urls'), name="business"),
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
]
答案 0 :(得分:0)
urlpatterns = [
path('',MainListView.as_view(),name='list'),
path('(<pk>\d+)(?:/(<slug>[\w\d-]+))',MainDetailSlugView.as_view(), name='List'),
path('list/',views.list_list),
path('lists/<int:pk>/',views.list_detail),
]
如上所示,您定义了两个适用于此处的网址
/list/
/lists/<int> # which applies to something like /lists/293749
您正在调用的URL是/List/list
,除非您使用类似
urlpatterns = [
path('list/', include('List.urls'))
]
耦合事物:
/List
,但URL定义为/list
答案 1 :(得分:0)
您在url.py文件的url中犯了一个小错误。 更改:
path('List',include('List.urls'), name="List"),
进入:
path('List/',include('List.urls'), name="List"),