Need a simple working ajax example for django forms

前端 未结 2 902
再見小時候
再見小時候 2020-12-28 23:16

Basically I need something similar to http://www.w3schools.com/jquery/jquery_ajax_get_post.asp done in django. I\'ve downloaded the samples and tested it locally with a loca

相关标签:
2条回答
  • 2020-12-28 23:55

    Check this example: Check this Link

    Models

    class Color(models.Model):
        color = models.CharField(max_length=256)
    
    class Auto(models.Model):
        type = models.CharField('auto type', max_length=256)
        colors = models.ManyToManyField(Color) 
    
    from django import forms
    from models import Color, Auto
    
        class AutoForm(forms.Form):
            TYPE_CHOICES = [('', '-- choose a type --'), ] + [(t.type, t.type) for t in Auto.objects.all()]
            COLOR_CHOICES = [(c.color, c.color) for c in Color.objects.all()]
            COLOR_CHOICES.insert(0, ('', '-- choose a vehicle type first --'))
    
            type = forms.ChoiceField(choices=TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'get_vehicle_color();'}))
            color = forms.ChoiceField(choices=COLOR_CHOICES)
        [Check this article][2] can be helpful
    

    Templates

    {% extends "base.html" %}
    {% block head %}
    <script type="text/javascript" src="/site_media/prototype.js"></script>
    <script type="text/javascript" src="/site_media/my_ajax_function.js"></script>
    {% endblock %}
    
    {% block content %}
        {% if form_was_valid %}
            {# ... show whatever... #}
        {% else %}
            <form action="/auto/reserve/" method="POST">
            <ul>
            {{ form.as_ul}}
            <li><label for="submit">&nbsp;</label>
            <input type="submit" id="submit" name="submit" value="Submit"/></li>
            </ul>
            </form>
        {% endif %}
    {% endblock %}
    

    Javascript

    function get_vehicle_color(){
        new Ajax.Request('/auto/ajax_purpose_staff/', { 
        method: 'post',
        parameters: $H({'type':$('id_type').getValue()}),
        onSuccess: function(transport) {
            var e = $('id_color')
            if(transport.responseText)
                e.update(transport.responseText)
        }
        }); // end new Ajax.Request
    }
    

    URL.py

    urlpatterns = patterns('mysite.auto.views',
        (r'^ajax_color_request/$', 'ajax_color_request'),
        # ... everything else...
    )
    
    
    def ajax_color_request(request):
        # Expect an auto 'type' to be passed in via Ajax and POST
        if request.is_ajax() and request.method == 'POST
            auto_type = Auto.objects.filter(type=request.POST.get('type', ''))
            colors = auto_type.colors.all() # get all the colors for this type of auto.
        return render_to_response('auto/ajax_color_request.html', locals())
    
    {% for c in colors %}
        <option value="{{ c.color }}">{{ c.color|title }}</option>
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-29 00:14

    OK..thx for your comments..I got it all sorted out..basically I just missed out on the {% csrf_token %} and csrfmiddlewaretoken:'{{ csrf_token }}'..just for the benefit of those who might be reading this..the new codes will look something like this

    the javascript:

    <script type="text/javascript">
    $(document).ready(function(){
    
      $("#my_form").submit(function(){
        $.post("",
        {name:"Donald Duck",
         city:"Duckburg",
         csrfmiddlewaretoken:'{{ csrf_token }}'
         },
        function(data,status){
          alert("Data: " + data + "\nStatus: " + status);
        })
        .fail(function(xhr) {
            console.log("Error: " + xhr.statusText);
            alert("Error: " + xhr.statusText);
        });
        return false;
      });
    
    });
    </script>
    

    the html:

    <form id="my_form" action="" method="post">{% csrf_token %}
    <input type="submit" value="Send">
    </form>
    
    0 讨论(0)
提交回复
热议问题