是否有一种特殊的方法可以将Django消息添加到当前模板中,并使用多个表单和调用同一页面?

oogrdqng  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(99)

我有一个消息模板:

messages.html
{% 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 | safe }}
        </li>
    {% endfor %}
  </ul>
{% endif %}

字符串
在我的模板中包含:

add_recipient.html
{% block content %}
    {% include 'myapp/messages.html' %}
    <div class="doc">
        <h2>Add Recipient</h2>
        <a class="btn btn-dark btn-lg" href="{% url 'myapp:recipient_list' 'A' %}">Back To List</a>
        <div class="form">
            <form method="post">
                {% csrf_token %}
                <table class="form form-table" style="font-size: x-large">
                    {{ recipient }}
                    {{ address }}
                    {{ demographics }}
                    {% if person_forms %}
                        {{ person_forms }}
                    {% endif %}
                </table>
                <div class="row d-flex justify-content-center m-4">
                    <button class="btn btn-primary btn-lg " type="submit">Add Recipient</button>
                </div>

            </form>
        </div>
    </div>

{% endblock content %}


以及:

edit_recipient.html
{% block content %}
    {% include 'myapp/messages.html' %}
    <div class="doc">
        <h2>Edit Recipient Details</h2>
        <div class="container-fluid m-0">
            <div class="row ">
                <div class="col-lg">
                    <a class="btn btn-dark btn-lg" href="{% url 'myapp:recipient_detail' recipient_id=recipient_id back_to=back_to %} ">BACK</a>
                </div>
            </div>
        </div>
        <div class="d-flex flex-row">
            <div class="d-flex flex-column mx-auto" >
                <form method="post">
                    {% csrf_token %}
                    <table class="form form-table" style="font-size: x-large">
                        {{ recipient_form }}
                        {{ address_form }}
                        {{ demo_form}}
                        {{ formset }}
                    </table>
                    <button class="btn btn-lg btn-primary" type="submit">Submit</button>
                </form>
            </div>
        </div>
    </div>
{% endblock content %}


然后我把它添加到视图中,这样:

add_recipient(request):
# in request.POST
                if person_forms.is_valid():

                    if get_total_num_forms(person_forms, operator.gt, 17) == demo_form_data[0]:
                        # Save forms
                        persons = person_forms.save(commit=False)
                        address.save()

                        # Apply address_id to and save recipient
                        recipient.recipient_address_id = address.id
                        recipient.phone = new_phone_number
                        recipient.save()
                        # Apply recipient_id to demo
                        demo.recipient_id = recipient.id
                        demo.save()

                        for person in persons:
                            person.recipient_id = recipient.id
                            person.save()

                        return redirect('myapp:recipient_list', 'A')

                    message = 'Form ages are WRONG!'
                    messages.error(request, message)

                    return render(request=request, template_name=template, context=context_dict)

                # Redirect back to add_recipient with forms
                return render(request=request, template_name=template, context=context_dict)


和/或

view edit_recipient
# in request.POST
 if demo_form_data[2] == len(formset):
    if check_ages_with_demographics(formset, demo_form_data):  # Forms where added and now need to be saved!!!!!!!!!
        # Need to check forms and save all
        update_object(recipient_form, recipient)
        update_object(AddressForm(request.POST or None), obj_models[1])
        update_object(DemographicsForm(request.POST or None), obj_models[2])
        # Need to check if adult and child forms match demo nums
        for i in range(len(formset)):
            if i < len(obj_models[3]):
                update_object(formset[i], obj_models[3][i])
            else:
                person = formset[i].save(commit=False)
                person.recipient_id = recipient_id
                person.save()

         return redirect('myapp:recipient_detail',
                          recipient_id=recipient.id,
                          back_to=back_to,)
    else:
        message = 'Added form age incorrect.'
        messages.error(request, message)
        forms = [recipient_form, address_form, demo_form, formset]
        return render(request=request, template_name=template,
                      context=get_render_context(form_names=form_names, forms=forms, kwargs=kwargs))


我的问题是,当用户输入了错误的表单年龄时,消息会显示在add_recipient上,但它仍然在表单页面上,以便他们可以修复它。但是编辑页面不会显示消息,但是当我将两个页面备份到包含消息模板的任何其他页面时,它会显示在那里。
我意识到这不是整个视图函数,但就我所知,实现是相同的。edit_recipient页面正在执行它应该执行的操作,清除表单数据并重新显示页面,以允许用户修改表单值,但它没有显示消息。任何帮助是非常感谢!
我试着将代码直接添加到edit_recipient.html中,而不是包含它,但没有成功。我甚至注解掉了message.html中的其他模板,这也不起作用。我试图通过年龄验证表格,因为我需要跟踪儿童和成人。因此,如果用户正在将成人添加到人口统计中,提交后,它会为具有年龄、种族和性别的人添加另一个表单,然后再次提交后,它会检查以确保新的人是成年人,反之亦然。表单实际上是按预期工作的,只是不是一个页面上的消息。

r1zhe5dt

r1zhe5dt1#

根据您提供的内容,“edit_recipient.html”页面可能没有显示邮件所需的上下文数据。您应该确保将消息上下文数据也传递给模板。
在视图中的“edit_recipient”函数确保在呈现模板时传递消息上下文数据
您的views.py应如下所示:

from django.contrib import messages

def edit_recipient(request):

    if demo_form_data[2] == len(formset):
        if check_ages_with_demographics(formset, demo_form_data):
            # your logic

        else:
            message = 'Added form age incorrect.'
            messages.error(request, message)
            forms = [recipient_form, address_form, demo_form, formset]
            context_dict = get_render_context(form_names=form_names, forms=forms, kwargs=kwargs)

            # Pass the messages context data to the template
            context_dict['messages'] = messages.get_messages(request)

            return render(request=request, template_name=template, context=context_dict)

def add_recipient(request):

    if person_forms.is_valid():
        if get_total_num_forms(person_forms, operator.gt, 17) == demo_form_data[0]:
            # your logic goes here again

        else:
            message = 'Form ages are WRONG!'
            messages.error(request, message)

            # Pass the messages context data to the template
            context_dict['messages'] = messages.get_messages(request)

            return render(request=request, template_name=template, context=context_dict)

字符串
现在,这两个函数都应该能够显示消息,只要确保“edit_recipient.html”也通过使用:

{% include 'myapp/messages.html'%}


我希望这对你有帮助。

相关问题