I have created a polls app with the Django tutorial and have added a REST API, again with the tutorial.
I think I have an error somewhere in my urlpatterns config because I can see only some pages, the rest give me an error.
My root url.py:
from django.urls import path, include
from polls import views, viewsets
urlpatterns = [
path('', include('polls.urls')),
path('polls/', include('polls.urls', namespace="polls")),
path('admin/', admin.site.urls),
]
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]
My app-level url.py:
from . import views, viewsets
from .viewsets import QuestionViewSet, UserViewSet, ResultsViewSet
from rest_framework import renderers
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'questions', viewsets.QuestionViewSet)
router.register(r'users', viewsets.UserViewSet)
router.register(r'results', viewsets.ResultsViewSet)
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('', include(router.urls)),
]
viewsets.py:
from django.utils import timezone
from .models import Choice, Question
from .serializers import QuestionSerializer, UserSerializer, ChoiceSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from rest_framework import permissions
from .permissions import IsOwnerOrReadOnly
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import viewsets
class QuestionViewSet(viewsets.ModelViewSet):
queryset = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
serializer_class = QuestionSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class ResultsViewSet(viewsets.ModelViewSet):
queryset = Choice.objects.all()
serializer_class = ChoiceSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'questions': reverse('question-list', request=request, format=format),
})
views.py:
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
def get_queryset(self):
#excludes any questions that aren't published yet.
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
models.py:
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
owner = models.ForeignKey('auth.User', related_name='questions', null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
def create(self, validated_data):
return Question.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.question_text = validated_data.get('question_text', instance.question_text)
instance.save()
return instance
def save(self, *args, **kwargs):
super(Question, self).save(*args, **kwargs)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
owner = models.ForeignKey('auth.User', related_name='choices', null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.choice_text
URLs that are OK:
http://localhost:8000/
http://localhost:8000/polls/
http://localhost:8000/polls/1/
http://localhost:8000/polls/1/results/
http://localhost:8000/polls/1/vote/
http://localhost:8000/users/ (why does this work as only API related link?!)
http://localhost:8000/api-auth/login/
http://localhost:800/admin/
URLs that are not OK:
http://localhost:8000/questions/
http://localhost:8000/results/
Please let me know if you need to see any other code.
Thanks in advance!