0

I've added the contact us functionality in the footer using inclusion tag and form on my website. It's working perfectly fine on all the pages except the "home" page, throwing this error:

Method Not Allowed (POST): /
Method Not Allowed: /
[11/Jul/2020 01:31:18] "POST / HTTP/1.1" 405 0

Following are the inclusion tag and the form:

@register.inclusion_tag('contact_us.html', takes_context=True)
def contact_form(context):
    request = context['request']
    context['success']=False
    if request.method == 'POST':
        form = ContactUsForm(request.POST)
        if form.is_valid():
            msg =form.save(commit=False)
            msg.contact_user =request.user
            msg.save()
            # messages.success(request, 'Your message has been successfully sent!')
            context['success']=True
    form = ContactUsForm()
    context['contact_form']=form
    return context
class ContactUsForm(forms.ModelForm):
    def __init__(self,*args,**kwargs):
        super(ContactUsForm,self).__init__(*args,**kwargs)
        self.fields['message'].widget.attrs['rows']=4
        self.fields['message'].widget.attrs['placeholder'] = 'Your Message'
        self.fields['message'].label =''

    class Meta:
        model =ContactUs
        fields =('message',)

Following is how the html for the contact us looks like:

{% load crispy_forms_tags %}
{% if success %}<div>Your Message has been sent Successfully!</div>{% endif %}
<form action="" method="POST" class="row mt-2">
    <div class="col-md-10">
        {% csrf_token %}
        {{contact_form|crispy}}
        </div>
        <div class="col-md-2">
        <button class="btn btn-brand ml-2" type="submit">Submit</button>
        </div>
</form>

It's throwing error 405 only on the home page.

jitesh2796
  • 164
  • 6
  • 14
  • A context processor will *not* run in case you submit the form. You thus should specifh the `
    ` to a view that will handle it properly.
    – Willem Van Onsem Jul 10 '20 at 20:19
  • Hi, I've added the html code as well, are you saying I need to attach it to some view?? – jitesh2796 Jul 10 '20 at 20:25
  • 1
    yes, you should not write the POST logic in the context processor. It will not ru anyway. You can use it to "inject" a form that you render. But you will need to define an extra view that will handle the form in case it is submitted. – Willem Van Onsem Jul 10 '20 at 20:26
  • Thanks Willem, it worked. The Home page view was a class based template view, I updated that to a function based view and it worked fine. – jitesh2796 Jul 10 '20 at 20:34

0 Answers0