Liondancer
Liondancer

Reputation: 16469

405 error with AJAX for submission

I am trying to perform ajax for my form in my Django project. I am pretty new to webdev in general so what I think I am supposed to do is have an ajax call POST in a specific url which I chose as /message/. When a POST request is sent, my view should respond to this request and update my database and also render some text within /message/. However I am getting 405 error.

enter image description here

urls.py:

from home.views import HomeView, contact_request_view

urlpatterns = patterns('',
    url(r'^$', HomeView.as_view(), name="home"),
    url(r'^message/', contact_request_view)
)

views.py:

class HomeView(generic.TemplateView):
    template_name = "home/home.html"

def contact_request_view(request):
    if request.method == 'POST':
        form = ContactForm()
        if form.is_valid():
            obj, created = User.objects.get_or_create(email=form.cleaned_data['email'],
                                                      first_name=form.cleaned_data['first_name'],
                                                      last_name=form.cleaned_data['last_name'])
            ContactRequest.objects.create(user=obj,
                                          message=form.cleaned_data['message'])
        return render(request, "message", "testing")
    return render(request, "message", "FAIL")

form.py:

class ContactForm(forms.Form):
    first_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(required=True, widget=forms.EmailField())
    message = forms.CharField(required=True, widget=forms.Textarea(attrs={'class': 'form-control contact-margin', 'rows': '8', 'placeholder': 'Message...'}))

JS:

var contactForm = document.getElementById("contact-form");
var firstName = contactForm.getElementById("firstname");
var lastName = contactForm.getElementById("lastname");
var email = contactForm.getElementById("email");
var message = contactForm.getElementById("message");

contactForm.submit(function() {
    var contactInfo = {
        first_name: firstName.val(),
        last_name: lastName.val(),
        email: email.val(),
        message: message.val()
    };
    $.ajax({
        type: 'POST',
        url: "/message/",
        data: contactInfo,
        success: function() {
            console.log("posted");
        },
        error: function() {
            console.log("failed")
        }
    });
    return false;
});

form:

<section id="contact">
  <div class="container">
    <div class="title-container">Contact Us</div>
    <div class="title-caption">Reach us at (415)-911-9999</div>
    <form class="contact-input" id="contact-form" method="post">
      {% csrf_token %}
      <div class="col-md-12">
        <div class="col-md-6">
          <div class="contact-input-margin form-group">
            <input id="firstname" class="form-control" placeholder="First name">
          </div>
          <div class="contact-input-margin form-group">
            <input id="lastname" class="form-control" placeholder="Last name">
          </div>
          <div class="contact-input-margin form-group">
            <input id="email" class="form-control" placeholder="Email">
          </div>
          <div class="contact-input-margin form-group">
            <input class="form-control" placeholder="Phone number">
          </div>
        </div>
        <div class="contact-input-margin col-md-6">
          <div class="form-group">
            <textarea id="message" rows="8" class="form-control contact-margin" placeholder="Message...">

            </textarea>
          </div>
        </div>
      </div>
      <input type="submit" value="Submit" class="btn btn-xl">
    </form>
  </div>
</section>

Upvotes: 0

Views: 262

Answers (3)

dazedconfused
dazedconfused

Reputation: 1342

You would need to create a form instance and populate it with data from the request:

def contact_request_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # if form is valid, you can process the data in form.cleaned_data
            ...

            return render(request, "message", "testing")
        else:
            do_some_stuff()  # if you `print(form.errors)` you can see what cause the errors
    return render(request, "message", "FAIL")

Also, you might want to take a look at ModelForm , so you can redeclare your ContactForm like this:

class ContactForm(ModelForm):
    class meta:
        model = User  

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)

After that, if form is valid, you can call form.save(), and django will create the User instance automatically for you.

Upvotes: 1

e-nouri
e-nouri

Reputation: 2626

Method Not Allowed because you have not defined the POST in your view, the error make sence. Your view needs the POST method to be declared:

class HomeView(generic.TemplateView):
    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

Upvotes: 2

martintrapp
martintrapp

Reputation: 819

You should send the csrf token with the post request in your JS code or you have to turn off the csrf protection on your message view with csrf_exempt() method like this url(r'^message/', csrf_exempt(contact_request_view)).

Upvotes: 1

Related Questions