重定向后来自模板的信息,Django-Python [英] Information from the template after redirection, Django - Python

查看:34
本文介绍了重定向后来自模板的信息,Django-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的视图,该视图允许我在Django模板中添加注释.

I have a simple view that allows me to add comments in my Django template.

if request.method == 'POST':
    review_form = ReviewForm(data=request.POST)
    if review_form.is_valid():
        rating = review_form.cleaned_data['rating']
        comment = review_form.cleaned_data['comment']
        user_name = review_form.cleaned_data['user_name']
        order_code = review_form.cleaned_data['order_code']
        review = Review()
        review.masseurs = masseur
        review.rating = rating
        review.comment = comment
        review.user_name = user_name
        review.order_code = order_code
        review.pub_date = datetime.datetime.now()
        review.save()

        return HttpResponseRedirect(reverse('app:masseur_detail', args=(masseur.id,)))

else:
    review_form = ReviewForm()

添加评论后,用户将被重定向到基本页面.我想在此表示感谢,并在此添加了评论.如何在视图中创建一个元素,该元素将检查是否刚刚添加了新注释(重定向之后).我试图使用类似'new_comment = review_form.save(commit = False)'的方法,但是它无法正常工作(或者我做错了什么).任何帮助将不胜感激.

After adding the comment, the user is redirected to the basic page. I would like to display a thank you and information here, the comment has been added. How can I create an element in my view that will check if a new comment has just been added (after redirection). I tried to use something like 'new_comment = review_form.save (commit = False)' but it does not work properly (or I am doing something wrong). Any help will be appreciated.

推荐答案

您可以执行以下操作

in views.py

 from django.contrib import messages
if request.method == 'POST':
    review_form = ReviewForm(data=request.POST)
    if review_form.is_valid():
        rating = review_form.cleaned_data['rating']
        comment = review_form.cleaned_data['comment']
        user_name = review_form.cleaned_data['user_name']
        order_code = review_form.cleaned_data['order_code']
        review = Review()
        review.masseurs = masseur
        review.rating = rating
        review.comment = comment
        review.user_name = user_name
        review.order_code = order_code
        review.pub_date = datetime.datetime.now()
        review.save()
        messages.success(request, 'Added successfully!')
        return HttpResponseRedirect(reverse('app:masseur_detail', args=(masseur.id,)))

else:
    review_form = ReviewForm()

在模板中添加此行

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
        {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
        {{ message }}
    </li>
    {% endfor %}
</ul>
{% endif %}

希望有帮助

这篇关于重定向后来自模板的信息,Django-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆