How to get multiple values from a template and update multiple fields in a rows of thesame table in django












1















I am working on a result processing website and I've been trying to update multiple fields in each row of table. User should be able to input updated CA Score and EXAM Score values and it should update each student's CA Score and EXAM Score values which has been submitted. image of page



Someone ask same question here trying to update a single field. I tried to work with the solution provided there but was unable to make it suit my need



template



<form action="" method="post"> {% csrf_token %}
{% for student in students %}
<tr>
<td>{{ student.id_number }}</td>
<td>
<input type="number" value="{{ student.ca }}" name="student_{{ student.id }}">
</td>
<td>
<input type="number" value="{{ student.exam }}" name="student_{{ student.id }}">
</td>
</tr>
{% endfor %}
<tr>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form>


view



def add_score_for(request, id):
if request.method == 'GET':
students = TakenCourse.objects.filter(course__allocated_course__lecturer__pk=request.user.id).filter(course__id=id)
context = { "students":students}
return render(request, 'result/add_score_for.html', context)

if request.method == 'POST':
data = request.POST.dict()
data.pop('csrfmiddlewaretoken', None)
for i in data.items():
obj = TakenCourse.objects.get(id=i[0].split("_")[1])
if not str(obj.ca) == str(i[1]): # if i do i[2] trying to get for exams it raise 'tuple index out of range'
obj.ca = i[1]
obj.save()









share|improve this question



























    1















    I am working on a result processing website and I've been trying to update multiple fields in each row of table. User should be able to input updated CA Score and EXAM Score values and it should update each student's CA Score and EXAM Score values which has been submitted. image of page



    Someone ask same question here trying to update a single field. I tried to work with the solution provided there but was unable to make it suit my need



    template



    <form action="" method="post"> {% csrf_token %}
    {% for student in students %}
    <tr>
    <td>{{ student.id_number }}</td>
    <td>
    <input type="number" value="{{ student.ca }}" name="student_{{ student.id }}">
    </td>
    <td>
    <input type="number" value="{{ student.exam }}" name="student_{{ student.id }}">
    </td>
    </tr>
    {% endfor %}
    <tr>
    <td><input type="submit" value="Save"></td>
    </tr>
    </tbody>
    </table>
    </form>


    view



    def add_score_for(request, id):
    if request.method == 'GET':
    students = TakenCourse.objects.filter(course__allocated_course__lecturer__pk=request.user.id).filter(course__id=id)
    context = { "students":students}
    return render(request, 'result/add_score_for.html', context)

    if request.method == 'POST':
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken', None)
    for i in data.items():
    obj = TakenCourse.objects.get(id=i[0].split("_")[1])
    if not str(obj.ca) == str(i[1]): # if i do i[2] trying to get for exams it raise 'tuple index out of range'
    obj.ca = i[1]
    obj.save()









    share|improve this question

























      1












      1








      1








      I am working on a result processing website and I've been trying to update multiple fields in each row of table. User should be able to input updated CA Score and EXAM Score values and it should update each student's CA Score and EXAM Score values which has been submitted. image of page



      Someone ask same question here trying to update a single field. I tried to work with the solution provided there but was unable to make it suit my need



      template



      <form action="" method="post"> {% csrf_token %}
      {% for student in students %}
      <tr>
      <td>{{ student.id_number }}</td>
      <td>
      <input type="number" value="{{ student.ca }}" name="student_{{ student.id }}">
      </td>
      <td>
      <input type="number" value="{{ student.exam }}" name="student_{{ student.id }}">
      </td>
      </tr>
      {% endfor %}
      <tr>
      <td><input type="submit" value="Save"></td>
      </tr>
      </tbody>
      </table>
      </form>


      view



      def add_score_for(request, id):
      if request.method == 'GET':
      students = TakenCourse.objects.filter(course__allocated_course__lecturer__pk=request.user.id).filter(course__id=id)
      context = { "students":students}
      return render(request, 'result/add_score_for.html', context)

      if request.method == 'POST':
      data = request.POST.dict()
      data.pop('csrfmiddlewaretoken', None)
      for i in data.items():
      obj = TakenCourse.objects.get(id=i[0].split("_")[1])
      if not str(obj.ca) == str(i[1]): # if i do i[2] trying to get for exams it raise 'tuple index out of range'
      obj.ca = i[1]
      obj.save()









      share|improve this question














      I am working on a result processing website and I've been trying to update multiple fields in each row of table. User should be able to input updated CA Score and EXAM Score values and it should update each student's CA Score and EXAM Score values which has been submitted. image of page



      Someone ask same question here trying to update a single field. I tried to work with the solution provided there but was unable to make it suit my need



      template



      <form action="" method="post"> {% csrf_token %}
      {% for student in students %}
      <tr>
      <td>{{ student.id_number }}</td>
      <td>
      <input type="number" value="{{ student.ca }}" name="student_{{ student.id }}">
      </td>
      <td>
      <input type="number" value="{{ student.exam }}" name="student_{{ student.id }}">
      </td>
      </tr>
      {% endfor %}
      <tr>
      <td><input type="submit" value="Save"></td>
      </tr>
      </tbody>
      </table>
      </form>


      view



      def add_score_for(request, id):
      if request.method == 'GET':
      students = TakenCourse.objects.filter(course__allocated_course__lecturer__pk=request.user.id).filter(course__id=id)
      context = { "students":students}
      return render(request, 'result/add_score_for.html', context)

      if request.method == 'POST':
      data = request.POST.dict()
      data.pop('csrfmiddlewaretoken', None)
      for i in data.items():
      obj = TakenCourse.objects.get(id=i[0].split("_")[1])
      if not str(obj.ca) == str(i[1]): # if i do i[2] trying to get for exams it raise 'tuple index out of range'
      obj.ca = i[1]
      obj.save()






      django django-models django-templates






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 11:04









      AIbrahimAIbrahim

      114




      114
























          2 Answers
          2






          active

          oldest

          votes


















          0














          In plain Django you would solve this using Formsets:
          https://docs.djangoproject.com/en/2.1/topics/forms/formsets/



          This will generate the markup (or allow you to generate the markup) you need to update multiple students which will then be updated on submit. It also allows to add the entries (you can disable this feature).






          share|improve this answer
























          • thanks for replying, I just try working with formset but i returns a single row instead of all the available rows in the model.

            – AIbrahim
            Nov 14 '18 at 15:38













          • you need to pass all rows as initial see docs.djangoproject.com/en/2.1/topics/forms/formsets/…

            – Risadinha
            Nov 15 '18 at 8:02











          • Thank you so much for the help but i resolved the problem using the above approach

            – AIbrahim
            Nov 16 '18 at 11:40



















          0














          Here is how i solved my problem, don't know if its the best way to do it but it did solve my issue



          views



          @lecturer_required 
          def add_score_for(request, id):
          current_semester = Semester.objects.get(is_current_semester=True)
          if request.method == 'GET':
          ...
          return render(request, 'result/add_score_for.html', context)

          if request.method == 'POST':
          ids = ()
          data = request.POST.copy()
          data.pop('csrfmiddlewaretoken', None) # remove csrf_token
          for key in data.keys():
          ids = ids + (str(key),) # gather all the all students id (i.e the keys) in a tuple
          for s in range(0,len(ids)): # iterate over the list of student ids gathered above
          score = data.getlist(ids[s]) # get list of score for current student in the loop
          ca = score[0] # subscript the list to get the fisrt value > ca score
          exam = score[1] # do thesame for exam score
          obj = TakenCourse.objects.get(student__pk=ids[s]) # get the current student data
          obj.ca = ca # set current student ca score
          obj.exam = exam # set current student exam score
          obj.total = obj.get_total(ca=ca,exam=exam)
          obj.grade = obj.get_grade(ca=ca,exam=exam)
          obj.comment = obj.get_comment(obj.grade)
          obj.save()
          return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))
          return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298726%2fhow-to-get-multiple-values-from-a-template-and-update-multiple-fields-in-a-rows%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            In plain Django you would solve this using Formsets:
            https://docs.djangoproject.com/en/2.1/topics/forms/formsets/



            This will generate the markup (or allow you to generate the markup) you need to update multiple students which will then be updated on submit. It also allows to add the entries (you can disable this feature).






            share|improve this answer
























            • thanks for replying, I just try working with formset but i returns a single row instead of all the available rows in the model.

              – AIbrahim
              Nov 14 '18 at 15:38













            • you need to pass all rows as initial see docs.djangoproject.com/en/2.1/topics/forms/formsets/…

              – Risadinha
              Nov 15 '18 at 8:02











            • Thank you so much for the help but i resolved the problem using the above approach

              – AIbrahim
              Nov 16 '18 at 11:40
















            0














            In plain Django you would solve this using Formsets:
            https://docs.djangoproject.com/en/2.1/topics/forms/formsets/



            This will generate the markup (or allow you to generate the markup) you need to update multiple students which will then be updated on submit. It also allows to add the entries (you can disable this feature).






            share|improve this answer
























            • thanks for replying, I just try working with formset but i returns a single row instead of all the available rows in the model.

              – AIbrahim
              Nov 14 '18 at 15:38













            • you need to pass all rows as initial see docs.djangoproject.com/en/2.1/topics/forms/formsets/…

              – Risadinha
              Nov 15 '18 at 8:02











            • Thank you so much for the help but i resolved the problem using the above approach

              – AIbrahim
              Nov 16 '18 at 11:40














            0












            0








            0







            In plain Django you would solve this using Formsets:
            https://docs.djangoproject.com/en/2.1/topics/forms/formsets/



            This will generate the markup (or allow you to generate the markup) you need to update multiple students which will then be updated on submit. It also allows to add the entries (you can disable this feature).






            share|improve this answer













            In plain Django you would solve this using Formsets:
            https://docs.djangoproject.com/en/2.1/topics/forms/formsets/



            This will generate the markup (or allow you to generate the markup) you need to update multiple students which will then be updated on submit. It also allows to add the entries (you can disable this feature).







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 14 '18 at 11:48









            RisadinhaRisadinha

            9,09615461




            9,09615461













            • thanks for replying, I just try working with formset but i returns a single row instead of all the available rows in the model.

              – AIbrahim
              Nov 14 '18 at 15:38













            • you need to pass all rows as initial see docs.djangoproject.com/en/2.1/topics/forms/formsets/…

              – Risadinha
              Nov 15 '18 at 8:02











            • Thank you so much for the help but i resolved the problem using the above approach

              – AIbrahim
              Nov 16 '18 at 11:40



















            • thanks for replying, I just try working with formset but i returns a single row instead of all the available rows in the model.

              – AIbrahim
              Nov 14 '18 at 15:38













            • you need to pass all rows as initial see docs.djangoproject.com/en/2.1/topics/forms/formsets/…

              – Risadinha
              Nov 15 '18 at 8:02











            • Thank you so much for the help but i resolved the problem using the above approach

              – AIbrahim
              Nov 16 '18 at 11:40

















            thanks for replying, I just try working with formset but i returns a single row instead of all the available rows in the model.

            – AIbrahim
            Nov 14 '18 at 15:38







            thanks for replying, I just try working with formset but i returns a single row instead of all the available rows in the model.

            – AIbrahim
            Nov 14 '18 at 15:38















            you need to pass all rows as initial see docs.djangoproject.com/en/2.1/topics/forms/formsets/…

            – Risadinha
            Nov 15 '18 at 8:02





            you need to pass all rows as initial see docs.djangoproject.com/en/2.1/topics/forms/formsets/…

            – Risadinha
            Nov 15 '18 at 8:02













            Thank you so much for the help but i resolved the problem using the above approach

            – AIbrahim
            Nov 16 '18 at 11:40





            Thank you so much for the help but i resolved the problem using the above approach

            – AIbrahim
            Nov 16 '18 at 11:40













            0














            Here is how i solved my problem, don't know if its the best way to do it but it did solve my issue



            views



            @lecturer_required 
            def add_score_for(request, id):
            current_semester = Semester.objects.get(is_current_semester=True)
            if request.method == 'GET':
            ...
            return render(request, 'result/add_score_for.html', context)

            if request.method == 'POST':
            ids = ()
            data = request.POST.copy()
            data.pop('csrfmiddlewaretoken', None) # remove csrf_token
            for key in data.keys():
            ids = ids + (str(key),) # gather all the all students id (i.e the keys) in a tuple
            for s in range(0,len(ids)): # iterate over the list of student ids gathered above
            score = data.getlist(ids[s]) # get list of score for current student in the loop
            ca = score[0] # subscript the list to get the fisrt value > ca score
            exam = score[1] # do thesame for exam score
            obj = TakenCourse.objects.get(student__pk=ids[s]) # get the current student data
            obj.ca = ca # set current student ca score
            obj.exam = exam # set current student exam score
            obj.total = obj.get_total(ca=ca,exam=exam)
            obj.grade = obj.get_grade(ca=ca,exam=exam)
            obj.comment = obj.get_comment(obj.grade)
            obj.save()
            return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))
            return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))





            share|improve this answer






























              0














              Here is how i solved my problem, don't know if its the best way to do it but it did solve my issue



              views



              @lecturer_required 
              def add_score_for(request, id):
              current_semester = Semester.objects.get(is_current_semester=True)
              if request.method == 'GET':
              ...
              return render(request, 'result/add_score_for.html', context)

              if request.method == 'POST':
              ids = ()
              data = request.POST.copy()
              data.pop('csrfmiddlewaretoken', None) # remove csrf_token
              for key in data.keys():
              ids = ids + (str(key),) # gather all the all students id (i.e the keys) in a tuple
              for s in range(0,len(ids)): # iterate over the list of student ids gathered above
              score = data.getlist(ids[s]) # get list of score for current student in the loop
              ca = score[0] # subscript the list to get the fisrt value > ca score
              exam = score[1] # do thesame for exam score
              obj = TakenCourse.objects.get(student__pk=ids[s]) # get the current student data
              obj.ca = ca # set current student ca score
              obj.exam = exam # set current student exam score
              obj.total = obj.get_total(ca=ca,exam=exam)
              obj.grade = obj.get_grade(ca=ca,exam=exam)
              obj.comment = obj.get_comment(obj.grade)
              obj.save()
              return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))
              return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))





              share|improve this answer




























                0












                0








                0







                Here is how i solved my problem, don't know if its the best way to do it but it did solve my issue



                views



                @lecturer_required 
                def add_score_for(request, id):
                current_semester = Semester.objects.get(is_current_semester=True)
                if request.method == 'GET':
                ...
                return render(request, 'result/add_score_for.html', context)

                if request.method == 'POST':
                ids = ()
                data = request.POST.copy()
                data.pop('csrfmiddlewaretoken', None) # remove csrf_token
                for key in data.keys():
                ids = ids + (str(key),) # gather all the all students id (i.e the keys) in a tuple
                for s in range(0,len(ids)): # iterate over the list of student ids gathered above
                score = data.getlist(ids[s]) # get list of score for current student in the loop
                ca = score[0] # subscript the list to get the fisrt value > ca score
                exam = score[1] # do thesame for exam score
                obj = TakenCourse.objects.get(student__pk=ids[s]) # get the current student data
                obj.ca = ca # set current student ca score
                obj.exam = exam # set current student exam score
                obj.total = obj.get_total(ca=ca,exam=exam)
                obj.grade = obj.get_grade(ca=ca,exam=exam)
                obj.comment = obj.get_comment(obj.grade)
                obj.save()
                return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))
                return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))





                share|improve this answer















                Here is how i solved my problem, don't know if its the best way to do it but it did solve my issue



                views



                @lecturer_required 
                def add_score_for(request, id):
                current_semester = Semester.objects.get(is_current_semester=True)
                if request.method == 'GET':
                ...
                return render(request, 'result/add_score_for.html', context)

                if request.method == 'POST':
                ids = ()
                data = request.POST.copy()
                data.pop('csrfmiddlewaretoken', None) # remove csrf_token
                for key in data.keys():
                ids = ids + (str(key),) # gather all the all students id (i.e the keys) in a tuple
                for s in range(0,len(ids)): # iterate over the list of student ids gathered above
                score = data.getlist(ids[s]) # get list of score for current student in the loop
                ca = score[0] # subscript the list to get the fisrt value > ca score
                exam = score[1] # do thesame for exam score
                obj = TakenCourse.objects.get(student__pk=ids[s]) # get the current student data
                obj.ca = ca # set current student ca score
                obj.exam = exam # set current student exam score
                obj.total = obj.get_total(ca=ca,exam=exam)
                obj.grade = obj.get_grade(ca=ca,exam=exam)
                obj.comment = obj.get_comment(obj.grade)
                obj.save()
                return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))
                return HttpResponseRedirect(reverse_lazy('add_score_for', kwargs={'id': id}))






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 16 '18 at 12:01

























                answered Nov 16 '18 at 11:55









                AIbrahimAIbrahim

                114




                114






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298726%2fhow-to-get-multiple-values-from-a-template-and-update-multiple-fields-in-a-rows%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine