相关文章推荐
聪明的领带  ·  jquery ...·  1 周前    · 
飞翔的枕头  ·  Jquery ajax ...·  3 天前    · 
爽快的可乐  ·  三剑客 awk sed ...·  1 年前    · 
讲道义的楼房  ·  java.lang.IllegalState ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have models, forms and views. I need ajax form request, when a room is selected to change the room information. I tried ajax but it doesn't work. I also use 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>

template

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

Please help me, thanks in advance.

view which handles this url '/hotel/rooms-view/' + pk + '/' if it is room_detail then you should create another one for ajax requests only – madzohan May 29, 2015 at 12:32 `cause in room_detail when request is post it tries to save form, when get it returns html, but you need serialized data – madzohan May 29, 2015 at 12:38

you should specify type of ajax request ... if you want post request to your view, then add it after $.ajax({ type: 'post',

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

You should call ajax request when your dropdown is changed like this,

 <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>
                See a basic example for Jquery change function for a select box jsfiddle.net/ajaikumark/howofrdj
– Ajai
                May 29, 2015 at 12:30
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.