Home > Net >  How to save checkbox value in django?
How to save checkbox value in django?

Time:08-20

I am using checkboxes in Html and everytime I refresh my page, the checkboxes are unchecked again. How do I prevent this from happening ? Do I have to use JS ? I tought about booleans fields but I don't really know how to implement them ... I looked at other threads and it talked about javascript, but I do not understand anything at all about it, nor how to implement it. Here is my code :

views.py :

'

@login_required(login_url='/login') 
def home(request):
check=False
MyToDo = Todo.objects.filter(user=request.user)
formtoDo = forms.TodoForm()


if request.method == 'POST' and 'todosub' in request.POST:
    
    formtoDo = forms.TodoForm(request.POST)
    if formtoDo.is_valid():
        todoit = formtoDo.save(commit=False)
        todoit.user = request.user
        todoit.save()
        
        return HttpResponseRedirect('/home?')
    [...]
    data ={'form': form, 'formtoDo': formtoDo, 'MyToDo': MyToDo, 'check':check}
return render(request, "capygenda/entries.html", data)

'

html :

 <form method="POST", >
       {% csrf_token %}
       <p>{{ formtoDo|crispy}} <button type="submit" name="todosub" >Add</button></p>
       
    
   </form>
   
   
       {% csrf_token %}
    
   {% for toto in MyToDo     %}
   
   <form method="POST">
     {% csrf_token %}
         <ul >
           <li >
             <input type="checkbox"  id="{{ toto.id }}" autocomplete="off"/>
             <label for="{{ toto.id }}" >
               <span ></span>
               <span >{{ toto }}</span>
             </label>
             <button  role="button"><a href="{% url 'delete_todo' toto.pk   %}" >Delete</a></button>
         </ul>
       </form>    

CodePudding user response:

Two steps:

  1. In your views, if the form is submitted i.e., when request.method == 'POST' is True, pass another parameter {'checked: 'checked'}:
if request.method == 'POST' and 'todosub' in request.POST:
    
    formtoDo = forms.TodoForm(request.POST)
    if formtoDo.is_valid():
        todoit = formtoDo.save(commit=False)
        todoit.user = request.user
        todoit.save()
        
        return HttpResponseRedirect('/home?')
    [...]

    # ---- here look at the last item ----
    data ={'form': form, 'formtoDo': formtoDo, 'MyToDo': MyToDo, 'check':check, 'checked':'checked'}

return render(request, "capygenda/entries.html", data
  1. In your template, place that variable as an attribute in the input HTML element:
 <input type="checkbox"  id="{{ toto.id }}" autocomplete="off" {{ checked }}/>

This way, the checked attribute of the input will be dynamically placed. If it was passed via POST method, you have it. Otherwise, it's just empty.

CodePudding user response:

add checked in the input field if you want it to keep it pre-checked or dependent on View values.

<input {% if checked %} checked{% endif %}"/>
  • Related