简体   繁体   中英

Why the 'post' method is not working in my django app?

I am using Django to develop a blog and when I wanted to get the contact informations, the post request seems not working at all. In the contacts view I don't do much I just wanted to make sure that the post request is working but it returns a Get request instead and the get method is working really fine
the javascript file

  //CONTACT FORM
$('#contactform').submit(function(){
  var action = $(this).attr('action');
  $("#message").slideUp(750,function() {
  $('#message').hide();
  $('#submit').attr('disabled','disabled');
  $.post(action, {
    name: $('#name').val(),
    email: $('#email').val(),
    comments: $('#comments').val()
  },
    function(data){
      document.getElementById('message').innerHTML = data;
      $('#message').slideDown('slow');
      $('#submit').removeAttr('disabled');
      if(data.match('success') != null) $('#contactform').slideUp('slow');
      $(window).trigger('resize');
    }
  );
  });
  return false;
});

view.py

from django.http.response import HttpResponse
from contact.forms import ContactForm
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
# Create your views here.
def contacts(request):
if request.method == "POST" and request.is_ajax:
    print('hello!!')
    
    return render(request, 'contact/contact.html')

forms.py

from django import forms
from .models import Contact
class ContactForm(forms.Form):
     class Meta:
         model = Contact
         fields = ['cont_name', 'cont_email', 'cont_message', 'cont_date']

models.py

from django.db import models
from datetime import datetime

class Contact(models.Model):
    cont_name = models.CharField( max_length = 10)
    cont_email = models.EmailField()
    cont_message = models.TextField(blank=False)
    cont_date = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.cont_name

contact.html

 <div class="container">
      <div class="row">
          <div class="col-md-6">
              <p class="lead">Sold old ten are quit lose deal his sent. You correct how sex several far distant believe journey parties. We shyness enquire uncivil affixed it carried to. </p>
              <p>End sitting shewing who saw besides son musical adapted. Contrasted interested eat alteration pianoforte sympathize was. He families believed if no elegance interest surprise an. It abode wrong miles an so delay plate.</p>
              
          </div>

          <div class="col-md-6">
              <div id="message"></div>
              <form method="post" action="{% url 'contacts' %}" id="ContactForm" class="main-contact-form wow">
                  {% csrf_token %}
                  <input type="text" class="form-control col-md-4" name="name" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name." />
                  <input type="text" class="form-control col-md-4" name="email" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address." />
                  <textarea name="comments" class="form-control" id="comments" placeholder="Your Message *" required data-validation-required-message="Please enter a message."></textarea>
                  <input class="btn btn-primary btn-theme" type="button" name="submit" value="Submit" />
              </form>
          </div>
      </div>
  </div>

urls.py

from django.urls import path, reverse
from . import views

urlpatterns = [
     path('', views.contacts, name= 'contacts'),

]

Your question is vague but it seems you want to make work an ajax post request in django. Can you try this:

$('#contactform').submit(function(){
  var action = $(this).attr('action');
  
  var name = $("#name").val()
  var email = $("email").val()
  var formData = {
    name: name,
    email: email
  }
  $.ajax({
    type: "POST",
    data: formData,
    url:action,
    beforeSend: function (data) {

    },
    success: function (data) {
        if (data){
            console.log("Working")
        }
    },
    error: function (data) {
     console.log("Not working")
   }

  })
  })

See if this works.

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