helloxielan 2014-11-20 08:37 采纳率: 0%
浏览 40

Django Ajax验证

i've been trying to figure out how to use ajax in my django for a while but I coulnt find a solution.

Here is my view.py:

from django.shortcuts import render, render_to_response, RequestContext, HttpResponseRedirect
from .forms import SignUpForm
from django.contrib import messages
# Create your views here.


def home(request):

    form = SignUpForm(request.POST or None)


    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        # messages.success(request, 'Thank you for joining!')
        # return HttpResponseRedirect('/thank-you/')


    return render_to_response("home.html",
                                 locals(),
                                  context_instance=RequestContext(request))

the is the model.py

from django.db import models
from django.utils.encoding import smart_unicode


# Create your models here.

class SignUp(models.Model):
    first_name = models.CharField(max_length=120, null=True, blank=True)
    last_name = models.CharField(max_length=120, null=True, blank=True)
    email = models.EmailField()
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)


    def __unicode__(self):
        return smart_unicode(self.email)

This is the html part

<form method='POST' action=''> {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' class='btn btn-success'>
</form>
</div>

I've tried many method but none of them is working . can someone help

Im trying to log a thank you message after the user submitted their information. I want it stay still instead of refreshing. and how to use ajax to replace the built in error message when the email field is empty.

</div>
  • 写回答

3条回答 默认 最新

  • weixin_33739541 2014-11-20 09:42
    关注

    You'll need to send an Ajax request using jQuery or XMLHttpRequest Object. (which I didn't see you doing in the code provided)

    For using jQuery, you'll need to do something like this:

    <script>
    $.ajax({
        type: "POST",
        url: "url_to_your_view",
        data: $('#id_of_your_form').serialize()
    }).done(function(msg) {
        log_thank_you_msg();  // log thank you message using JavaScript or jQuery
    });    
    </script>
    

    Also, in your view, you can do something like this to return your thank you message:

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        ...
        return render_to_response("home.html", RequestContext(request, {'message': 'thank you'}))
    else:
        handle_the_error()  # Return error messages or do some error handling
    
    评论
  • weixin_33743880 2014-11-20 10:24
    关注

    Here is jQuery AJAX post with CSRF token:

    $(function () {
    
    
        $('.btn btn-success').on('click', function (e) {
                // add csrf token to your post
                var csrf = document.cookie.match(/csrftoken=([\w]+)/);
                var data = $('.styled-form').serialize();
                var request = $.ajax({
                        url: window.location.pathname,
                        type: 'post',
                        'csrfmiddlewaretoken' : csrf? csrf[1] : null,
                        'data': data
                });
                // callback handler that will be called on success
                request.done(function (response, textStatus, jqXHR){
                    console.log('Success')
                    // log a message to the console
                });
    
                // callback handler that will be called on failure
                request.fail(function (jqXHR, textStatus, errorThrown){
                    // log the error to the console
                    console.error(
                        "The following error occured: "+
                        textStatus, errorThrown
                    );
                });
            }
        });
    

    in view:

    if form.is_valid():
        if request.is_ajax():
            save_it = form.save(commit=False)
            save_it.save()
            # messages.success(request, 'Thank you for joining!')
            # return HttpResponseRedirect('/thank-you/')
    
    评论
  • weixin_33701617 2014-11-20 11:43
    关注

    use these steps to get your desired result ::

    views.py"

    def home(request):
        if request.method=="POST" and request.is_ajax():
            form = SignUpForm(request.POST)
            if form.is_valid():
                save_it = form.save(commit=False)
                save_it.save()
                return render(request, "thanks.html",{}) 
            else :
                return render(request, "form.html",{'form':form}) 
    
        form = SignUpForm()
        return render(request, "home.html",{'form':form}) 
    

    then your home.html should be like this:

    <html>
    # your contents here
    <body>
    <div id="ajax-form-div">
    <form method='POST' id="ajax-form-date" action='your url here'> {% csrf_token %}
        {{ form.as_p }}
        <button id="submit-btn" class='btn btn-success'>Submit</button>
    </form>
    </div>
    </body>
    </html>
    

    then you create a new template name "form.html":

    <form method='POST' action=''> {% csrf_token %}
        {{ form.as_p }}
        <input type='submit' class='btn btn-success'>
    </form>
    

    Then you create a thanks page like this "thanks.html":

    <div>
    <p> Thank you!!!!!!!!!!!!!!!!!!! </p>
    </div>
    

    and at the end you write your ajax:

    <script>
    $.ajax({
        type: "POST",
        url: "URL OF SAME METHOD OR .",
        data: $('#ajax-form-date').serialize()
    }).success(function(responce) {
        $("#ajax-form-div").html(responce)
    });    
    </script>
    

    if form will get valid you will get your thank you mas and if form is not valid you will again get a new form with error msg.

    Please take care of jquery should be load on your page. and ajax will get call.

    Hope this will help to you.

    评论

报告相同问题?

悬赏问题

  • ¥15 存储过程或函数中的结果集类型变量如何使用。
  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信