简体   繁体   中英

Using a Django form on more than one HTML page

In this latest project I'm using a simple contact form, which resolves to the url /email/. I also want to include this form on the homepage. In the past I've used get_context_data when I have a page class in a view, but I'm using cookiecutter with crispy forms for the first time and don't know where to do that, or even if that is the right thing to do.

Here's the forms.py:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions
from crispy_forms.layout import Submit

class ContactForm(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True)
    content = forms.CharField(required=True, widget=forms.Textarea)

    # the new bit we're adding
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('contact_name', placeholder="Full Name", autofocus=""),
            Field('contact_email', placeholder="Email Address"),
            Field('content', placeholder=""),
            Submit('sign_in', 'Submit', css_class="btn btn-info"),
            )
        self.fields['contact_name'].label = "Your name:"
        self.fields['contact_email'].label = "Your email:"
        self.fields['content'].label = "Your message:"

...and that renders perfectly at /email/. How do I get this form to appear on the front page also?

In case it's needed, here's the urls.py:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^email/$', views.email, name='email'),
    url(r'^success/$', views.success, name='success'),
]

You can do the following:

  1. Create a form.html file and write the following code in it.

"

{% for field in form %}
 <div class="form-group">
     <div class="inner form">
         <span class="text-danger small">{{ field.errors }}</span>
     </div>
     <label class="control-label col-sm-2" for="song_title">{{ 
                  field.label_tag }}</label>
     <div class="col-sm-10">{{ field }}</div>
 </div>
{% endfor %}

2. Include this template in your front page using the following on your front page template

{% include 'form.html' %}
  1. Pass your form instance in your views to the template you want the form to showUp, this will ensure that this form shows up on the front-page template as well.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM