Josh
Josh

Reputation: 2478

How do I initialise my form in Django?

I have created a contact form on my homepage but the form does not show until I click on the submit form the first time. I.e. calling the get method. I would like to keep it as a separate view to my homepage so that when re-clicking 'submit' it does not have an impact on my homepage. Is there a way to load my 'def email' when my homepage loads?

template form

<form method="post" action="{% url 'home_page:email' %}">
            {% csrf_token %}
{#            {% bootstrap_form form.as_p %}#}
            {{ form.as_p }}
            <input type="submit" value="Sign Up" class="btn btn-default">
        </form>

urls

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

views

class HomePage(MessageMixin, TemplateView):
    template_name = "index.html"

def email(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, ['[email protected]'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, "index.html", {'form': form})

Upvotes: 0

Views: 34

Answers (1)

Ajmal Noushad
Ajmal Noushad

Reputation: 946

Include the form in the HomePage view context. Like this:

class HomePage(MessageMixin, TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
         context = super(HomePage, self).get_context_data(**kwargs)
         context['form'] = ContactForm(None)
         return context

Upvotes: 1

Related Questions