python - Django在模板中调用DetailView和RedirectView的方法
问题描述
我正在尝试进入 Django 并陷入DeatailView
困境RedirectView
我制作了以下模板来渲染帖子,并启用帖子详细视图和点赞按钮。当我单击其中一个Like
或Detail
按钮时,不会发送任何请求。我尝试改变不同的方法,但这也无济于事。我试图了解我是否在模板或视图逻辑中弄错了。
{% 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())),
]
任何意见表示赞赏。
解决方案
为了提交表单,按钮的类型应该是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 函数来提交表单,但除非您有特定的原因,否则最好让浏览器为您完成工作。
推荐阅读
- ios - UserDefaults 是否避免冗余写入磁盘?
- python - 如何将此 python 转换文件修复为应用程序 - 仍未找到解决方案
- github - 在从另一台机器推送项目之前,我是否需要从 Github 拉取?
- windows - Git Bash 终端回复致命:“C:/....”:不是文档目录
- android - 上一个片段edittext焦点问题
- javascript - 如果没有 PCI DSS 1 级合规性,我可以通过 GooglePay 使用 PayPal
- javascript - 如何创建 Dynamic React 响应式轮播
- javascript - react 应用程序中带有参数的 URL 在新的浏览器窗口或选项卡中不起作用
- c# - httpget 控制器和本地化
- python - 比较重复的行