用AJAX提交405错误

时间:2014-12-10 07:53:40

标签: python ajax django

我正在尝试在我的Django项目中为我的表单执行ajax。我对webdev一般都是新手,所以我认为我应该做的是在我选择/message/的特定网址中有一个ajax调用POST。发送POST请求时,我的view应响应此请求并更新我的数据库,并在/message/内呈现一些文本。但是我得到405错误。

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;
});

形式:

<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>

3 个答案:

答案 0 :(得分:2)

方法不允许,因为您没有在视图中定义POST,错误发生了。您的视图需要声明POST方法:

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)

答案 1 :(得分:1)

您应该在JS代码中发送带有帖子请求的 csrf令牌,或者您必须使用 csrf_exempt()方法关闭邮件视图中的csrf保护这个url(r'^message/', csrf_exempt(contact_request_view))

答案 2 :(得分:1)

您需要创建一个表单实例并使用请求中的数据填充它:

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")

另外,您可能需要查看ModelForm ,所以你可以像这样重新宣布你的ContactForm

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

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

之后,如果表单有效,您可以调用form.save(),django将自动为您创建User实例。