django视图中的函数不获取任何数据

lx0bsm1f  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(127)

一切都很好,把它放在似乎在www.example.com发布功能views.py只是没有得到任何数据。另外,如何在纯js使提交按钮没有重新加载页面?views.py:

from django.shortcuts import render
from rest_framework.decorators import api_view
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from datetime import datetime
from .models import Category, Text

@csrf_exempt
@api_view(['POST'])
def post_data(request):
    print(request)
    text_name = request.POST.get('text_name')
    text_category_id = request.POST.get('text_category')
    text_content = request.POST.get('text_content')
    text_char_count = len(text_content)
    text_category = Category.objects.get(id=text_category_id)
    text = Text(name=text_name, category=text_category, content=text_content,
                char_count=text_char_count, created_at=datetime.now())
    text.save()
    return Response({'id': text.id, 'date': text.created_at})

def home(request):
    categories = Category.objects.all()
    return render(request, 'index.html', context = {"categories": categories})

index.html:

<div>
    <form method="post" class="form">
        {% csrf_token %}
        <input type="text_name" placeholder="title" required/>
        <select id="text_category" name="text_category" required>
            {% for category in categories %}
                <option value="{{ category.pk }}">{{category.title}}</option>
            {% endfor %}
        </select>
        <textarea id="text" type="text_content" placeholder="text" required></textarea>
        <input type="submit">Submit</input>
        </form>
        <p>Количество символов: <span id="char-count">0</span>
    </div>
    <script src="{% static 'form.js' %}"></script>

form.js:

const saveForm = document.getElementById('form')
const charCount = document.getElementById('char-count')
const textContent = document.getElementById('text')

textContent.addEventListener('input', () => {
    charCount.textContent = textContent.value.length
    console.log(saveForm)
})

saveForm.addEventListener('sumbit', async (event) => {
    event?.preventDefault();

    const form = new FormData(saveForm)
    console.log(form)
    const response = await fetch('http://127.0.0.1:8000/api/text-form/', {
        method: 'POST',
        body: form,
    })
    const data = await response.json()
    return data
})

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home),
    path('api/text-form/', views.post_data)
]

如果我运行这段代码,在浏览器中一切正常,我在控制台中得到代码200

kuhbmx9i

kuhbmx9i1#

你试过用request.data访问数据吗?我想这是Django REST中的数据,而不是放在request.POST

相关问题