No POST response when using checkbox form in my Dj

2019-09-03 17:04发布

Hey there, I am trying to delete Events as chosen by a by a user using check boxes to check of which events they want to be deleted. But for some reason whenever I call request.POST.get('event_list') Nothing is received even though boxes are checked and I end up with nothing. Here is my template and the view that should be deleting the chosen events.

 {% if event_list %}
       {% for event in event_list%}
               {%csrf_token%}
               <input type="checkbox" name="event_list"
id="event{{ forloop.counter }}" />
               <label for="event{{ forloop.counter }}">{{ event.title }}</
label><br />
       {% endfor %}
       <input type = 'submit' value = 'delete checked'>
       </form>
       <p>{{removal}}<p/>    {%comment%} this is what should be
removed{%endcomment%}
       {% if delete_error %}
               <p>{{delete_error}}</p>
           {% endif %}

views.py

def EventDelete(request):
       removal = request.POST.get('event_list')
       if removal:
               removal.delete()
       else:
               delete_error = "You didn't delete anything"
       return redner_to_response("detail.html", {'delete_error':
delete_error, 'removal': removal},
context_instance=RequestContext(request))

Im not sure why removal doesn't have anything in it, shouldn't it have the titles of the events in it? Unfortunately I don't know much about html and its workings :( I would really appreciate the help :) I feel like it is a simple fix and im just missing a small detail. Thanks :)

1条回答
趁早两清
2楼-- · 2019-09-03 17:53

The checkboxes have no value so you'll just get "on" sent to the server.

This:

<input type="checkbox" name="event_list"
 id="event{{ forloop.counter }}" />

should read

<input type="checkbox" name="event_list"
 id="event{{ forloop.counter }}" value="{{ forloop.counter }}" />

And then (once the server has received a list of ids), your code for processing it looks wrong, you need to somehow load the list of ids, and work out what to delete. You probably want something like

removal = request.POST.get('event_list')
for id in removal:
     event = get_object_or_404(Event, pk=id)
     event.delete()

I think you have a fair bit to learn! Check out firebug for monitoring what is actually being sent back to your server. Go to w3schools to learn about forms, and read the django documentation for handling the deletion.

查看更多
登录 后发表回答