Salut je suis entrai de créer mon blog avec le framework django et c'est difficile pour moi d'insérer la clé secondaire de l'article dans le Table Commentaire
views.py
code ajaxCode:def indexView(request): form = FriendForm() friends = Friend.objects.all() return render(request, "blog/testajax.html", {"form": form, "friends": friends}) def postFriend(request): # request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": # get the form data form = FriendForm(request.POST, ser_instance=Article.objects.get(pk=article.id)) # save the data and after fetch the object in instance if form.is_valid(): instance = form.save() # serialize in new friend object in json ser_instance = serializers.serialize('json', [ instance, ]) # send to client side. return JsonResponse({"instance": ser_instance}, status=200) else: # some form errors occured. return JsonResponse({"error": form.errors}, status=400) # some error occured return JsonResponse({"error": ""}, status=400)
Code:$("#friend-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call console.log(serializedData); $.ajax({ type: 'POST', url: "{% url 'blog:post_friend' %}", data: serializedData, success: function (response) { $("#contact-form").trigger('reset'); $("#succes").text('Vore message à bien été envoyé').css('background-color', 'lightblue'); }, error: function (response) { alert(response["responseJSON"]["error"]); } }) })
-----