1

I am trying to use Boostrap Modal to pop up an edit form that should send the thought and its id to my views function using Ajax, edit, and save it. However, when I press the Save Changes button on my modal, nothing happens. Being very new to this, I can not figure out exactly where to go on the internet so it would be great for me if anyone here could direct me on what to read and what I'm doing wrong.

my html -

<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
     <div class="modal-content">
     <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLongTitle">Edit</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
          </button>
     </div>
     <div class="modal-body">
          <form method = "POST" enctype= multipart/form-data id = "editt">
              {% csrf_token %}
              <textarea id = 'thought' style="resize:none" type = "text" placeholder = "{{ obj.thought }}." rows = "5" cols = "40" name = "thought" required></textarea><br>
      </div><br>

      <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      <a type = "button" data-catid = "{{ obj.id  }}"><button type="button" class="btn btn-primary submit" id = "upload-form-btn">Save changes</button></a>

          </form>
      </div>
      </div>

    <script type="text/javascript"> 
         $('.submit').click(function(event) {
            var id = $(this).parent().attr("data-catid");
            var thought = $("#thought").val();
            alert(id + "datas  "+thought)
            event.preventDefault();
            $.ajax({
                type: "POST",
                url: 'edit',
                data: {
                    'thought': thought,
                    'id': id,
                    'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()
                },
                contentType: false, // add this to indicate 'multipart/form-data'
                success: function(response) {
                alert('Form Submitted');
                location.reload();
                },
                error: function(data) {
                //alert('Form submission failed');
                }
            });

            });

    </script>

my views.py's edit function:

   if request.method == "POST":
       thought = request.POST['thought']
       id = request.POST['id']
       thought_x = Thought.objects.get(pk = id)
       form = ThoughtForm(request.POST or None, instance = thought_x)
       if form.is_valid():
           form.save()

my urls.py:

urlpatterns = [ path('edit',views.edit, name = 'edit'),
]+ static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) 

Models.py showing the model I am trying to update:

class Thought(models.Model):
    thought = models.CharField( max_length=300)
    done = models.BooleanField(default = False)
    date = models.DateTimeField(auto_now = True)
    manager = models.ForeignKey(User, on_delete =models.CASCADE, default = None)

 
  • You have many errors inside your jquery codes . Start with checking errors inside browsers console . – Swati Apr 14 '21 at 09:20
  • Thanks a lot for your comment! I did not realize the mistakes before. I will be fixing them and updating the code here if it still does not work. – shakirul islam Apr 14 '21 at 16:29
  • Your code is still not right . I have made [jsfiddle](https://jsfiddle.net/Lmv467y9/) use that jquery code and try again. – Swati Apr 15 '21 at 04:32
  • 1
    Also , as you are using ajax you cannot redirect from your django code do that part inside success function of ajax . – Swati Apr 15 '21 at 04:33
  • Thanks a lot for all the help. I replaced my code with yours and now there's an alert message, but I keep getting an error saying "Forbidden (CSRF token missing or incorrect.): /retro/edit".Could you suggest on that? I changed the code according to your directions. – shakirul islam Apr 15 '21 at 14:35
  • Hi, change `'{{ csrf_token }}'` to `$("[name=csrfmiddlewaretoken]").val()` . – Swati Apr 16 '21 at 04:11
  • Hello, thanks for your response. Changed the code but I am still facing the same error. – shakirul islam Apr 16 '21 at 17:14
  • 1
    print and see what does `$("[name=csrfmiddlewaretoken]").val()` has i.e : `alert($("[name=csrfmiddlewaretoken]").val())` . – Swati Apr 16 '21 at 17:23
  • this is being printed as a csrf value: wd5e2IQUHbU5MJorJj02LGeHnVvjYntZjvk4ZON8zGnl06g0gFijHYCgSh2TH2kx – shakirul islam Apr 16 '21 at 20:51
  • see if this value matches with `{% csrf_token %}` inside form modal . Just open browser element tab and scroll down to that element and verify same. – Swati Apr 17 '21 at 04:22
  • Yes, they match. What does it mean? – shakirul islam Apr 17 '21 at 17:52
  • it should work then if they match .. i am not sure what might be problem here . – Swati Apr 18 '21 at 13:10
  • Oh, thank you! I will try to solve it, and ask here again if I face new questions! Thank you for all the help. – shakirul islam Apr 19 '21 at 16:36
  • @Swati, I could get it to work. I had to remove ```contentType: false ```. I got the solution from this post - https://stackoverflow.com/a/36292539. Thanks a lot for all your help! I just finished my first project. – shakirul islam Apr 22 '21 at 12:06
  • 1
    **Explanation**(Copied from the link above): The arguments must be sent to Django as urlencoded with Content-Type application/x-www-form-urlencoded. Whereas, if you set processData: false it won't encode the POST parmaters and contentType: false will send ajax POST request as text/plain. – shakirul islam Apr 22 '21 at 12:28

0 Answers0