0

I have a pretty simple contact us form but the success_url is not working. The page isn't getting redirected to home after successful form submission.

I've followed the documentation available here https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-editing/

class ContactFormView(SuccessMessageMixin, FormView):
    form_class = ContactForm
    template_name = 'contact.html'
    success_message = 'Thank you!'
    success_url = reverse_lazy('home')

    def form_valid(self, form):       
        form.send_email()
        return super(ContactFormView, self).form_valid(form)

form_valid is being called but redirection to sucess_url doesn't happen and there are no errors.

Thanks for your help.

-------------UPDATED-----------------

forms.py

class ContactForm(forms.Form):
    name = forms.CharField(widget = TextInput(attrs={'placeholder': 'Your Name'}))
    email = forms.CharField(widget = EmailInput(attrs={'placeholder': 'Email'}))
    phone = forms.CharField(widget = TextInput(attrs={'placeholder': 'Phone'}))
    comment = forms.CharField(widget = forms.Textarea(attrs={'placeholder': 'Please write a comment'}))

    def send_email(self):
        # send email using the self.cleaned_data dictionary
        print("email sent!")

urls.py

import web.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),    
    url(r'^contact/', web.views.ContactFormView.as_view(), name='contact'),
    url(r'^$', web.views.home, name='home')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

contact.html

<div class="as-form">
                    <form method="post" class="myform" action="{% url 'contact' %}">
                        {% csrf_token %}
                        {% if form.errors %}{{ form.errors }}{% endif %}       
                        <p> {{form.name}} </p>
                        <p> {{form.phone}} </p>
                        <p> {{form.email}} </p>
                        <p class="as-comment"> {{form.comment}} </p>
                        <hr>
                        <p class="as-submit"> <input type="submit" value="Submit" class="as-bgcolor"> </p>
                    </form>
                </div>
Chirdeep Tomar
  • 4,281
  • 8
  • 37
  • 66

1 Answers1

0

I don't know how you set it up but the below works brilliantly (Django 1.10, Python 3.5)

# urls.py

urlpatterns = [
    url(r'^$', home_view, name='home'),
    url(r'^form/$', ContactFormView.as_view(), name='contact')
]


# forms.py

class ContactForm(forms.Form):
    name = forms.CharField(max_length=20)

    def send_email(self):
        print('Email sent!')


# views.py
# Your ContactFormView as is


# contact.html

<form action="" method="post">{% csrf_token %}
    {% if form.errors %}{{ form.errors }}{% endif %}
    {{ form.as_p }}
</form>
nik_m
  • 11,825
  • 4
  • 43
  • 57