【发布时间】:2022-12-06 02:27:28
【问题描述】:
每个人!我有 模型.py
class Post(models.Model):
...
status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='Activated')
...
网址.py
app_name = 'posts'
urlpatterns = [
...
path('<int:pk>/update/', views.PostUpdateView.as_view(), name='update_status')]
视图.py
class PostUpdateView(UpdateView):
model = Post
template_name = 'post_detail.html'
def change_status(self):
if request.method == "POST":
post = Post.objects.filter(id=self.id)
if post.status == 'Activated':
post.status = 'Deactivated'
post.save()
elif post.status == 'Deactivated':
post.status = 'Activated'
post.save()
return redirect('posts:post_detail')
posts_detail.html
...
<form action="{% url 'posts:update_status' post.id %}" method="post">
{% csrf_token %}
<button type="button">
{% if post.status == 'Activated' %}
Deactivate
{% else %}
Activate
{% endif %}</button>
</form>
...
我想切换按钮“激活/停用”上的字段并重定向到同一页面。目前有一个按钮,单击时没有任何变化。好吧,也许重定向有效,但状态不会切换。我假设 views.py 是错误的,但不知道在哪里。
我这样试过
@require_http_methods(['POST'])
def update_status(request, id):
if post.status == 'Activated':
Post.objects.filter(id=id).update(status='Deactivated')
elif post.status == 'Deactivated':
Post.objects.filter(id=id).update(status='Activated')
return redirect('posts:post_detail')
但这也不管用。 我知道这些是类似的方式,但我没有更多的想法。
【问题讨论】:
-
@RobertBradley 不,我需要通过点击按钮来切换
-
@ilnarkz,知道了。