django ajax form onchange select

时间:2015-05-29 12:14:02

标签: jquery ajax django python-3.x django-forms

我有模特,表格和观点。当选择房间来更改房间信息时,我需要ajax表格请求。我试过ajax,但它没有用。我也使用jQuery。

<script type="text/javascript">
  $(document).ready(function(){
$('#roomform').change(function() {
    request_url = '/hotel/rooms-view/' + pk + '/';
    $.ajax({
        url: request_url,
        success: function(data){
            $('#id_room').html('<option selected="' + "selected" + '">' + '' +'</option>');
            for(var i = 1; i<=data[1]; i++) 
                $('#id_room').append('<option value="' + i + '">' + i +'</option>');
        }, 
        errors: function(e) {
            alert(e);
        }
    })
})
</script>

模板

<form class="form-inline reservation-horizontal clearfix" role="form" method="post" action="" name="reservationform" id="bookingform">{% csrf_token %}
       <div class="row">                    

                <div class="form-group room">
                  <label for="room">{% trans 'room type' %}</label>
                  <select class="form-control" name="room" id="room">
                            <option value={{form.room}}</option>
                    </select>
                </div>

             <div class="form-group">
               <label for="from_date">{% trans 'checkin' %}</label></div> 

         <input name="from_date" type="text" id="from_date" value="" class="form-control"/>
            </div>

       <div class="form-group">
        <label for="to_date">{% trans 'checkout' %}</label>
             <input name="to_date" type="text" id="to_date" value="" class="form-control"/></div>

 <button type="submit" id="book" class="btn btn-primary btn-block"> Book</button>         
</form>

models.py

class Room(models.Model):
    status = models.BooleanField('Status',default=True)
    name = models.CharField('Name', max_length=100, unique=True)

class Book(models.Model):
    date = models.DateTimeField('Created',auto_now_add=True)
    from_date = models.DateField('Check-in')
    to_date = models.DateField('Check-out')
    room = models.ForeignKey(Room, related_name='booking')

forms.py

class BookForm(forms.ModelForm):
      from_date = forms.DateField(label='check-in')
      to_date = forms.DateField(label='check-out')
      adult = forms.IntegerField(label='adult')
      room = forms.ModelChoiceField(queryset=Room.objects.filter(status=True),widget=form.Select(attrs={'onchange':'refresh();'}))
      fname = forms.CharField(label='last name')
      lname = forms.CharField(label='first name')
      email = forms.EmailField(label='email')
      phone = forms.IntegerField(label='phone')
      message = forms.Textarea()

views.py#UPDATE

def room_detail(request,pk):
    room = get_object_or_404(Room,pk=pk)
    if request.method == 'POST':
        form = BookForm(request.POST,room=room)
        if form.is_valid():
            s = form.save(commit=True)          
            s.save()
            return redirect(request.path)
    else:
        form = BookForm()

    rooms = Room.objects.get(id=pk)

    start_dates = rooms.booking.values_list('from_date',flat=True)
    end_dates = rooms.booking.values_list('to_date',flat=True)
    dates = [start + timedelta(days=i) for start, end in zip(start_dates,end_dates) for i in range((end-start).days+1)]

    c = {}
    c['form'] = form
    return render_to_response('rooms_detail.html',c)

请提前帮助我。

2 个答案:

答案 0 :(得分:1)

你应该指定ajax请求的类型 ...如果你想要发布请求到你的视图,那么在$ .ajax之后添加它({类型: &#39;后&#39;,

来自django docs

class JSONResponseMixin(object):
    def render_to_response(self, context):
        return self.get_json_response(self.convert_context_to_json(context))

    def get_json_response(self, content, **httpresponse_kwargs):
        return HttpResponse(
            content,
            content_type='application/json',
        )

    def convert_context_to_json(self, context):
        return json.dumps(context)


class SomeAjaxView(View, JSONResponseMixin):
    model = Room

    @method_decorator(require_ajax)
    @method_decorator(require_POST)
    def dispatch(self, request, *args, **kwargs):
        obj_pk = request.POST.get('room_pk')
        self.object = get_object_or_404(self.model, pk=obj_pk)

        return super(SomeAjaxView, self).dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object.status = request.POST.get('status')
        self.object.name = request.POST.get('name')

        # same way you can change self.object.booking    
        self.object.save()

        context = {
            'result': 'success',
        }

        return self.render_to_response(context)

答案 1 :(得分:0)

当你的下拉列表改变时,你应该调用ajax请求,

 <script type="text/javascript">
  $(document).ready(function(){
    $('#room').change(function() {
    request_url = '/hotel/rooms-view/' + pk + '/';
    $.ajax({
      url: request_url,
      success: function(data){
      $('#id_room').html('<option selected="' + "selected" + '">' + '' +'</option>');
      for(var i = 1; i<=data[1]; i++) //data[1] contains no of sem
      $('#id_room').append('<option value="' + i + '">' + i +'</option>');
      }, 
      errors: function(e) {
      alert(e);
    }
    })
  })
</script>