1

I am creating a Django app for a To do List. I am using a bootstrap modal with Json for the Insertion into database. However, when I click the submit button, it says that data has been submitted into the database, but when I check the database, nothing is there.

urls.py:

urlpatterns = [
    path('', TaskListView.as_view(), name='task_list'),
    re_path(r'^create/$', views.task_create, name='task_create'),
]

views.py:

@login_required
def task_create(request):
    data = dict()
#, data=request.POST
    if request.method == 'POST':
        form = TaskForm(request.user, data=request.POST)
        if form.is_valid():
            form.save(commit=False)
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
    else:
        form = TaskForm(request.user)

    context = {'form': form}
    data['html_form'] = render_to_string('partial_task_create.html',
        context,
        request=request
    )
    return JsonResponse(data)

JavaScript:

$("#modal-task").on("submit", ".js-task-create-form", function () {
    var form = $(this);
    // {% url 'task_create' %} ................. 
    $.ajax({
      url: form.attr("action"),
      data: form.serialize(),
      type: form.attr("method"),
      dataType: 'json',
      success: function (data) {
        if (data.form_is_valid) {
          alert("Task created!");  // <-- This is just a placeholder for now for testing
        }
        else {
          $("#modal-task .modal-content").html(data.html_form);
        }
      }
    });
    return false;
  });

section of main template :

<div class="modal fade" id="modal-task">
    <div class="modal-dialog">
        <div class="modal-content">
        </div>
    </div>
</div>  

partial template for modal:

{% load widget_tweaks %}
<form method="post" action="{% url 'task_create' %}"  class="js-task-create-form" novalidate>
  {% csrf_token %}
  <div class="modal-header">
    <h4 class="modal-title" style="margin-left:90px;">Create a new Task</h4>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>    
  </div>
  <div class="modal-body">
    {% for field in form %}
      {% if field.id_for_label == "id_is_completed" %}
        <div class="form-check{% if field.errors %} has-error{% endif %}">
          <label class="form-check-label">          
            {% render_field field class="form-check-input" %} {{ field.label }}        
          </label>        

          {% for error in field.errors %}
            <p class="help-block">{{ error }}</p>
          {% endfor %}
        </div>
        <br />
      {% else %}
        <div class="form-group{% if field.errors %} has-error{% endif %}">
          <label for="{{ field.id_for_label }}">{{ field.label }}</label>

          {% render_field field class="form-control" %}

          {% for error in field.errors %}
            <p class="help-block">{{ error }}</p>
          {% endfor %}
        </div>   
      {% endif %}    
    {% endfor %}
  </div>
  <div class="modal-footer">
    <button type="submit" class="btn btn-primary">Create Task</button>
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>    
  </div>
</form>

models.py:(imports are removed)

class TaskForm(ModelForm):

    parent = forms.ModelChoiceField(queryset=Task.objects.all(), empty_label="---None---", required=False)


    class Meta:
        model = Task
        fields = ['task_title', 'task_description', 'is_completed', 'categories', 'parent']   


    def __init__(self, user, *args, **kwargs):        
        super(TaskForm, self).__init__(*args, **kwargs)
        self.fields['categories'].queryset = Categories.objects.filter(Q(user_id__isnull=True) | Q(user_id=user.id))
David.B
  • 370
  • 6
  • 16
  • Try to change this `form.save(commit=False)` to this `form.save(commit=True)` – Matej Feb 16 '20 at 15:14
  • @Matej when I tried that, it raised an error, `django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null")` – David.B Feb 16 '20 at 15:21
  • Have a look at what the commit flag is used for [here](https://stackoverflow.com/questions/12848605/django-modelform-what-is-savecommit-false-used-for) may help. – GTBebbo Feb 16 '20 at 15:25
  • Essentially, the `commit=false` stops the model from being inputted into the database allowing you to use a model object with null fields that in the database cannot be null – GTBebbo Feb 16 '20 at 15:27

0 Answers0