python - 将应用程序中的联系表单插入 Django 中的类 View

标签 python django django-forms

如果你有这样的看法

class Index(TemplateView):
    template_name = 'index.html'

其中 index.html 具有此结构

{% block content %}
    {% include "content.html" %}
{% content %}

如何在 content.html 中包含来自联系人应用的此 View ?

def contactForm(request):
    #....some form processing here
return render(request, "contact.html", {'form': form})

所以在 content.html 中,当提交成功时,您有一个联系表单,它只是停留在 content.html 上,表示成功。 谢谢。

最佳答案

您可以使用 FromView,它们旨在显示和验证基本表单。 您可以在 form_valid 或 form invalid 上创建一些自定义逻辑。 如果默认行为没问题,请不要使用它们。

有关成功消息,请查看 https://docs.djangoproject.com/en/2.2/ref/contrib/messages/

from django.urls import reverse_lazy
from django.views.generic import FormView
from django.contrib.messages.views import SuccessMessageMixin

class Index(SuccessMessageMixin,FormView):
    template_name = 'index.html'
    form_class = ContactForm()
    #name of your index view defined in urls.py
    success_url = reverse_lazy('name_of_your_index_view')
    success_message = "Success"


    #OPTIONAL:if you want some custom logic if the form is valid
    def form_valid(self, form):
        #custom logic here
        return super(Index,self).form_valid(form)

    #OPTIONAL:for custom logic if the form is invalid
    def form_invalid(self, form):
        #custom logic here
        return super(Index,self).form_invalid(form)

在 html 中不要忘记放一些类似的东西:

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

关于python - 将应用程序中的联系表单插入 Django 中的类 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55803916/

相关文章:

python - 调试 py2exe 创建的 library.zip,无需访问原始源

python - 替换字典中的键

python - 如何使用带有信号的 Django 模型继承?

Django 1.11 水平选择字段

python - Django 。 UserCreationForm 未正确呈现

python - 使用 Python 将数据字节 append 到二进制文件

Python:为什么具有两个参数的未绑定(bind)方法的行为不同于类方法?

python - Mac osx Django PIL 错误/usr/bin/cc 重新安装时出现文件错误

python - 无法使用 def clean() 运行表单集验证

javascript - 如何以内联形式使用 "django-autocomplete-light"