返回数据集作为 Postman 请求的表格。

huangapple go评论57阅读模式
英文:

Try to Return dataset as a table with request of postman

问题

以下是您的内容的翻译:

我想使用Postman进行请求,获取所有书籍的表格作为返回,但我找不到方法来实现这一点。非常感谢

这是我的书籍模型:

class Book(models.Model):
    name = models.CharField(max_length=100)
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    publication_date = models.DateField()
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
    description = models.TextField()

    def __str__(self):
        return self.name

这是我的视图:

class AddBookAPIView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'book.html'

    @method_decorator(login_required(login_url='login/'))
    def post(self, request):
        book_serializer = BookSerializer(data=request.data)
        if book_serializer.is_valid():
            book_serializer.save()
            return redirect('home')

        return Response({'message': book_serializer.errors})

    @method_decorator(login_required(login_url='login/'))
    def get(self, request):
        book = Book()
        serializer = BookSerializer(book)
        return Response({'serializer': serializer, 'book': book})

这是我的模板(我尝试为显示所有书籍创建另一个URL,我认为模板也是错误的):

{% load rest_framework %}
<title>书籍</title>

{% block title %><h3>查看书籍</h3>{% endblock %}

{% block content %}
<form class="form-inline" method="post" novalidate>
    {% csrf_token %}
    {% render_form serializer %}
</form>
{% endblock %}

请注意,上面的翻译是您提供的代码的中文翻译。如果您有任何其他问题或需要进一步的帮助,请随时告诉我。

英文:

I wanna Request with postman and get a table of all books as return but I can't find a way to do this. Thanks a lot

This is my model of books:

class Book(models.Model):
    name = models.CharField(max_length=100)
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    publication_date = models.DateField()
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
    description = models.TextField()

    def __str__(self):
        return self.name

And This is my View:

class AddBookAPIView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = &#39;book.html&#39;

    @method_decorator(login_required(login_url=&#39;login/&#39;))
    def post(self, request):
        book_serializer = BookSerializer(data=request.data)
        if book_serializer.is_valid():
            book_serializer.save()
            return redirect(&#39;home&#39;)

        return Response({&#39;message&#39;: book_serializer.errors})

    @method_decorator(login_required(login_url=&#39;login/&#39;))
    def get(self, request):
        book = Book()
        serializer = BookSerializer(book)
        return Response({&#39;serializer&#39;: serializer, &#39;book&#39;: book})

And this is my Template(I try make another url for showing all books and I think template is worng too):

{% load rest_framework %}
&lt;title&gt; Books &lt;/title&gt;

{% block title %}&lt;h3&gt; View Books &lt;/h3&gt;{% endblock %}

{% block content %}
&lt;form class=&quot;form-inline&quot; method=&quot;post&quot; novalidate&gt;
    {% csrf_token %}
    {% render_form serializer %}
&lt;/form&gt;
{% endblock %}

答案1

得分: 1

首先,您可以在类本身的上方使用 @method_decorator,使用 name="dispatch",如下所示:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

@method_decorator(login_required(login_url='login/'), name='dispatch')
class AddBookAPIView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'book.html'

    def post(self, request):
        book_serializer = BookSerializer(data=request.data)
        if book_serializer.is_valid():
            book_serializer.save()
            return redirect('home')

        return Response({'message': book_serializer.errors})

    def get(self, request):
        book = Book.objects.all()
        serializer = BookSerializer(book, many=True)
        return Response({'serializer': serializer, 'books': serializer.data})

其次,尝试在 BookSerializer 中使用 many=True,并使用 Book.objects.all() 来检索所有 Book 模型的实例,如下所示:

book = Book.objects.all()
serializer = BookSerializer(book, many=True)

尝试修改模板,以便显示所有书籍的列表,如下所示:

{% load rest_framework %}
<title>Books</title>

{% block title %}
    <h3>View Books</h3>
{% endblock %}

{% block content %}
    <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Publication Date</th>
                <th>Publisher</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            {% for book in books %}
                <tr>
                    <td>{{ book.name }}</td>
                    <td>{{ book.publication_date }}</td>
                    <td>{{ book.publisher }}</td>
                    <td>{{ book.description }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}
英文:

At first, you can simply apply @method_decorator just above the class itself using name=&quot;dispatch&#39;.

Secondly, try to use many=True in BookSerializer and also use Book.objects.all() to retrieve all instances of Book model, like the following:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

@method_decorator(login_required(login_url=&#39;login/&#39;), name=&#39;dispatch&#39;)
class AddBookAPIView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = &#39;book.html&#39;

    def post(self, request):
        book_serializer = BookSerializer(data=request.data)
        if book_serializer.is_valid():
            book_serializer.save()
            return redirect(&#39;home&#39;)

        return Response({&#39;message&#39;: book_serializer.errors})

    def get(self, request):
        book = Book.objects.all()
        serializer = BookSerializer(book, many=True)
        return Response({&#39;serializer&#39;: serializer, &#39;books&#39;: serializer.data})

Try to modify the template so that it would show the list of all books, like the following:

{% load rest_framework %}
&lt;title&gt;Books&lt;/title&gt;

{% block title %}
    &lt;h3&gt;View Books&lt;/h3&gt;
{% endblock %}

{% block content %}
    &lt;table class=&quot;table&quot;&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;Name&lt;/th&gt;
                &lt;th&gt;Publication Date&lt;/th&gt;
                &lt;th&gt;Publisher&lt;/th&gt;
                &lt;th&gt;Description&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
            {% for book in books %}
                &lt;tr&gt;
                    &lt;td&gt;{{ book.name }}&lt;/td&gt;
                    &lt;td&gt;{{ book.publication_date }}&lt;/td&gt;
                    &lt;td&gt;{{ book.publisher }}&lt;/td&gt;
                    &lt;td&gt;{{ book.description }}&lt;/td&gt;
                &lt;/tr&gt;
            {% endfor %}
        &lt;/tbody&gt;
    &lt;/table&gt;
{% endblock %}

huangapple
  • 本文由 发表于 2023年3月9日 23:32:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定