[Answered ]-Django save a series of question and its corresponding answer set to database

1👍

Second edit:

class SetData(APIView):
    def post(self, request):
        q_num = request.GET.get('q_num', False)
        for i in range(int(q_num)):
            question=Question(text=request.POST['question_text_{}'.format(i)])
            question.save()

            for j in range(4)
                Answer(
                text=request.POST['answers_{}_{}].format(i, j),
                        question=question,
                ...).save()

this is how you pass question total number via your request:

<form action="{% url 'add_test' internship.id  %}?p_num=set this with js" method="POST" >

to set q_num with js, you need to select your "form element" and edit it’s action. something like:

<form action="{% url 'add_test' internship.id  %}" method="POST" >

...

document.getElementById("add_test_form").action += '?q_num=' + num_of_qu;

you won’t need to change your url.


First edit:

I can’t help you with javascript but here’s how you get data from a post requst in django:
(This is a class based view, not much different from function based.)

class SetData(APIView):
    def post(self, request):
        test_num_questions = 
        request.POST['test_num_questions']
        # or if for example you wanna check if a submit input
        # (name='mysubmit') is clicked (in this case, you're
        # not sure if request.POST['test_num_questions']
        # returns True or error:
        
        mysubmit = 
        request.POST.get('mysubmit', False)
        # returns False if it there's no
        # request.POST['mysubmit']

Btw, why don’t you use django forms or even better, django model forms?

Leave a comment