Невозможно отправить данные на веб-сервер. "Не найдено: /api/posts", 404

Я новичок во фреймворке Django REST и все еще пытаюсь разобраться в нем.

Я пытаюсь разработать приложение для настольного компьютера и сайт форума, где приложение для настольного компьютера могло бы отправлять данные на сайт форума, в результате чего создавались бы новые сообщения/темы. В настоящее время, когда я пытаюсь отправить данные с помощью настольного приложения на веб-сайт, я получаю следующее сообщение в cmd:

"POST /api/posts HTTP/1.1" 404 4155 Не найдено: /api/posts

У меня есть это в моем urls.py

from django.urls import path, include
from .views import ThreadListView, ThreadDetailView, CreateThreadView, CreatePostView, PostViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'posts', PostViewSet)

urlpatterns = [
    path('', ThreadListView.as_view(), name='thread_list'),
    path('thread/<int:pk>/', ThreadDetailView.as_view(), name='thread_detail'),
    path('thread/create/', CreateThreadView.as_view(), name='create_thread'),
    path('thread/<int:pk>/post/', CreatePostView.as_view(), name='create_post'),
    path('accounts/', include('accounts.urls')),
]

# include the urls generated by the router
urlpatterns += router.urls

serializers.py:

from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

views.py:

class CreatePostView(CreateView):
    model = Post
    fields = ['content']

    def form_valid(self, form):

        # Get the thread object base on the url parameter 'pk'
        thread = Thread.objects.get(pk=self.kwargs['pk'])

        # Set the thread for the post
        form.instance.thread = thread

        form.instance.author = self.request.user
        # Save the post
        form.instance.save()

        # update the latest post date field in the thread model
        thread.latest_post_date = form.instance.created_at
        thread.save()

        # increase the user's post count by 1
        self.request.user.post_count += 1
        self.request.user.save()

        #form.instance.thread_id = self.kwargs['pk']
        return super().form_valid(form)
    
    def get_success_url(self):
        return reverse_lazy('thread_detail', kwargs={'pk': self.kwargs['pk']})
    

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all() 
    serializer_class = PostSerializer

Для настольного приложения у меня есть api.py:

import requests

def send_data_to_server(data):
    # Define the url of the api endpoint
    url = "http://127.0.0.1:8000/api/posts"

    # Send the HTTP POST request with the data
    """
    requests.post() is a function provided by the requests library in Python. 
    It is used to send an HTTP POST request to the specified URL.
    """
    response = requests.post(url, json=data)

    # Check if the request was successful
    if response.status_code == 201:
        print("Dataset successfully!")
    else:
        print("Failed to send data. Status code:", response.status_code)

Внутри main.py у меня есть кнопка 'send', которая связана с методом send_data:

def send_data(self):
        # example data to send (replace with the actual data later)
        data = {
            "content": "This is the data to send",
            "thread": 1,
            "author": 1,
            }
        send_data_to_server(data)

Когда я пытаюсь нажать на кнопку "Отправить" (send_data), я получаю ответ от сайта: Not Found: /api/posts [19/Apr/2024 23:29:01] "POST /api/posts HTTP/1.1" 404 4155

И от api.py: Не удалось отправить данные. Код состояния: 404

О, а это модель Post, которая у меня есть:

class Post(models.Model):
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True)

Где я ошибся?

Мое предположение состоит в том, что ошибка находится где-то в urls.py, но сейчас я чувствую себя совершенно потерянным.

Вернуться на верх