【问题标题】:How to render a form from another django app including error handling如何从另一个 django 应用程序呈现表单,包括错误处理
【发布时间】:2017-02-14 05:31:36
【问题描述】:

在我的登录页面/主页上,我想添加一个联系表单和一个订阅时事通讯表单。由于我想将两种表单的逻辑保留在不同的应用程序中,我想知道如何在用户输入错误的情况下使用 Django 的内部表单错误处理。与标准表单错误处理类似,我希望登录页面在表单字段旁边重新加载错误。如果逻辑保留在同一个应用程序中,这相当容易,但是当逻辑在另一个应用程序中时,我无法理解如何执行此操作。这是基本布局:

项目/views.py:

from django.views.generic.base import TemplateView

from contact.forms import ContactForm
from newsletter.forms import NewsletterForm


class HomeView(TemplateView):
    template_name = "home.html"
    contact_form = ContactForm()
    newsletter_form = NewsletterForm()
    title = "Home"

联系人/forms.py

from django import forms

from .models import Contact


class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = ['contact_name', 'contact_email', 'content']
        widgets = {
            'contact_name': forms.TextInput(attrs={'placeholder': 'Your name'}),
            'contact_email': forms.TextInput(attrs={'placeholder': 'Your Email address'}),
            'content': forms.Textarea(attrs={'placeholder': 'Your message'}),
        }

联系人/models.py

from django.db import models


class Contact(models.Model):
    contact_name = models.CharField(max_length=120)
    contact_email = models.EmailField()
    content = models.TextField()
    timestamp = models.TimeField(auto_now_add=True, auto_now=False)

    def __str__(self):
        return self.contact_name + self.timestamp

联系人/views.py

from django.shortcuts import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views import View

from .forms import ContactForm


class SendContactForm(View):
    form_class = ContactForm

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            print("all ok")
            return HttpResponseRedirect(reverse_lazy('home'))
        else:
            print(form.contact_name.errors)
            return HttpResponseRedirect(reverse_lazy('home'))

所以现在的问题是联系人(或时事通讯)视图和项目视图必须如何处理 Django 正常内部表单处理的错误(在不正确的输入字段旁边添加错误消息)。

感谢您的帮助!

更新: 我想分享我最终使用的解决方案。也许有一个最佳实践是如何在首页上显示多个表单,但在各自的应用程序中处理逻辑。但是,这最终对我有用。

项目/views.py:

from django.views.generic.base import TemplateView

from contact.forms import ContactForm
from newsletter.forms import NewsletterForm


class HomeView(TemplateView):
    template_name = "home2.html"
    title = "Home"

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        try:
            old_contact_form = self.request.session["contact_form"]
        except:
            old_contact_form = None
        try:
            old_newsletter_form = self.request.session["newsletter_form"]
        except:
            old_newsletter_form = None
        context["contact_form"] = ContactForm(old_contact_form)
        context["newsletter_form"] = ContactForm(newsletter_form)
        return context

联系人/views.py:

from django.shortcuts import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views import View

from .forms import ContactForm


class SendContactForm(View):
    form_class = ContactForm

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            print("all ok")
        else:
            request.session["contact_form"] = request.POST
            return HttpResponseRedirect(reverse_lazy("home"))

在各自的时事通讯中也是如此。使用会话对我有用。

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    这可能是我的解决方案之一。如果表单验证失败,则将表单作为上下文发送回

    if form.is_valid():
       print("all ok")
       return HttpResponseRedirect(reverse_lazy('home'))
    else:
       print(form.contact_name.errors)
       return Render(request, '/path/to/your/tempalate', context={'form': form})
    

    您可以执行以下操作来捕获模板上的错误 主页.html

    <div class="fieldWrapper">
        {{ form.contact_name.errors }}
        <label for="{{ form.contact_name.id_for_label }}">Email subject:</label>
        {{ form.contact_name }}
    </div>
    <div class="fieldWrapper">
        {{ form.contact_email.errors }}
        <label for="{{ form.contact_email.id_for_label }}">Your message:</label>
        {{ form.contact_email }}
    </div>
    

    【讨论】:

    • 感谢您的回答。但这不会重定向回主页,因此在发送表单后您将拥有不同的 URL。我想要某种重定向方案以保留在以前的 URL 中,但将逻辑保留在另一个应用程序中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2011-07-16
    • 2011-11-17
    • 1970-01-01
    相关资源
    最近更新 更多