代码之家  ›  专栏  ›  技术社区  ›  Steve

Django-使用另一个应用程序中的表单-问题创建重定向

  •  1
  • Steve  · 技术社区  · 8 年前

    我的项目中有一个联系人应用程序。为了在主页中使用该应用程序中的联系人表单,我在视图中创建了这个。py:

    from django.views import generic
    from contact.forms import ContactForm
    
    class HomePage(generic.TemplateView):
        template_name = "home.html"
    
        def get_context_data(self, *args, **kwargs):
            context=super(HomePage, self).get_context_data(*args, **kwargs)
            context['form'] = ContactForm
    
            return context
    

    以下是视图中的定义。联系人应用程序的副本:

    def contact(request):
        form_class = ContactForm
    
        if request.method == 'POST':
            form = form_class(data=request.POST)
    
            if form.is_valid():
                contact_name = request.POST.get('contact_name', '')
                contact_email = request.POST.get('contact_email', '')
                form_content = request.POST.get('content', '')
    
                template = get_template('contact/contact_template.txt')
                context = dict({'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content,})
    
                content = template.render(context)
    
                email = EmailMessage(
                    "New contact form submission",
                    content,
                    "Your website" +'',
                    ['you@company.com'],
                    headers = {'Reply-To': contact_email }
                )
                email.send()
                return render(request, 'contact/thank_you.html')
    
        return render(request, 'contact/contact.html', {
            'form': form_class,
        })
    

    2 回复  |  直到 8 年前
        1
  •  1
  •   Ykh    8 年前

    action="contact/" action="{% url contact:contact %}" here 是url resovle doc。

    您可以通过基于类的视图简化代码,如 FormView CreateView

    from django.views.generic import FormView, CreateView
    
        2
  •  0
  •   Sachin Bahal    8 年前

        def get_success_url(self):
            return reverse('url-name')
    

    如果有效,请告诉我。

    推荐文章