首页 > 解决方案 > Django在模板中调用DetailView和RedirectView的方法

问题描述

我正在尝试进入 Django 并陷入DeatailView困境RedirectView

我制作了以下模板来渲染帖子,并启用帖子详细视图和点赞按钮。当我单击其中一个LikeDetail按钮时,不会发送任何请求。我尝试改变不同的方法,但这也无济于事。我试图了解我是否在模板或视图逻辑中弄错了。

{% extends 'base.html' %}
{% block content %}
    {% for post in object_list %}
    <div class="card" style="width: 40rem;">
        <img src = "{{ post.image.url }}" style="height: 40rem;">
        <div class="card-body">
            <h5 class="card-tittle">{{post.author.username}}</h5>
            <p class="card-text">{{ post.description }}</p>
            <p class="card-text">Likes : {{ post.likes.count }}</p>
            <p class="id">Post_id: {{ post.id }}</p>
            <div class="btn-group-vertical">
                {% if user.is_authenticated %}
                    <form action="{% url 'like_post' %}" method="POST">
                        {% csrf_token %}
                        <button type="button" class="btn btn-secondary">Like</button>
                    </form>
                {% endif %}
                <form action="{% url 'detail' pk=post.id %}" method="GET">
                    <button type="button" class="btn btn-secondary">Detail</button>
                </form>
                <!-- <button type="button" class="btn btn-secondary">down</button> -->
            </div>
        </div>
    </div>
    {% endfor %}
{% endblock %}

帖子views.py文件

class PostDetail(DetailView):
    model = Post

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        print(context.items())
        return context

class PostLikeUpvote(RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        post_id = kwargs.get('id')
        post = get_object_or_404(Post, id=post_id)
        user = self.request.user
        if user.is_authenticated():
            post.likes.add(user)
        url_redirect = post.get_redirect_url()
        return url_redirect

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
    path('new/', PostCreate.as_view(), name='new'),
    path('', PostList.as_view(), name='list'),
    path('posts/', PostList.as_view(), name='list'),
    path('like_post/', PostLikeUpvote.as_view(), name='like_post'),
    path('posts/<pk>/', PostDetail.as_view(), name='detail'),
    path('bot/webhook', csrf_exempt(BotView.as_view())),
]

任何意见表示赞赏。

标签: pythondjango

解决方案


为了提交表单,按钮的类型应该是submit,而不是button

{% if user.is_authenticated %}
<form action="{% url 'like_post' %}" method="POST">
    {% csrf_token %}
    <button type="submit" class="btn btn-secondary">Like</button>
</form>
{% endif %}

否则它是一个简单的按钮,例如可以运行 JavaScript 函数,但它不会(自动)提交表单。当然,您可以编写一个 JavaScript 函数来提交表单,但除非您有特定的原因,否则最好让浏览器为您完成工作。


推荐阅读