How to stop __init__ of a class based view executing twice in django?

让人想犯罪 __ 提交于 2020-04-18 03:44:11

问题


I have shuffled the questions and corresponding options in the exam. Once student has wriiten the exam score will be displayed, and I want to show the student their answer sheet in the same way as they have seen while writing the exam with their answers and correct answers. So I decided to use random.seed().

Why init() is executing twice ?

[12/Mar/2020 14:08:58] "GET /exam/4/ HTTP/1.1" 200 11103
[12/Mar/2020 14:41:15] "GET / HTTP/1.1" 200 5059
init seed =  13
student now writing the exam with seed =  13
[12/Mar/2020 14:41:24] "GET /exam/3/ HTTP/1.1" 200 13156
init seed =  57
saving seed = 57
[12/Mar/2020 14:42:04] "POST /exam/3/ HTTP/1.1" 200 59

views.py

class ExamDetailView(LoginRequiredMixin, DetailView):
    model = Exam #context_object_name = 'exam'

    def __init__(self, *args, **kwargs):
        super(ExamDetailView, self).__init__(*args, **kwargs)
        self.seed = random.randint(1, 100)
        print("init seed = ", self.seed)

    def setup(self, *args, **kwargs):
        super().setup(*args, **kwargs)
        print(dir)

    def get_context_data(self, **kwargs):
        context = super(ExamDetailView, self).get_context_data(**kwargs)
        try:
            self.seed = ResultPerExam.objects.get(student_id = self.request.user.id, exam_id = self.kwargs[self.pk_url_kwarg]).seed #checking sudent has already written the exam or not
            print("seed read from ResultPerExam is ", self.seed)
            context["has_written"] = True
            random.seed(self.seed)
            print("student already writen exam with seed = ", self.seed)
        except ResultPerExam.DoesNotExist:
            context["has_written"] = False
            random.seed(self.seed)
            context["seed"] = self.seed
            print("student now writing the exam with seed = ", self.seed)
        return context

    def post(self, request, *args, **kwargs):
        eid = request.POST['exam']
        exam = Exam.objects.get(id = eid)
        res = exam.subject + " " + exam.skillType + " exam done!"
        res += "\n"
        res += "<h1>You have scored "
        score = 0
        result = ResultPerExam()
        result.student_id = request.user.id
        result.exam_id = eid
        result.que_pick_ans = ""
        for q in exam.question_set.all():
            if q.ans == request.POST.get(str(q.id)):
                score += 1
                result.que_pick_ans += str(q.id) + ":1, "
            else:
                result.que_pick_ans += str(q.id) + ":0, "
        result.marks = score
        print("saving seed =", self.seed)
        result.seed = self.seed
        result.save()
        res += str(score) + "</h1>"
        return HttpResponse(res, content_type="text/html")

exam-detail.html

<form method=POST %}">
    {% csrf_token %}
     <div style="background-color:lightgreen">
        <h1>
            {% if has_written %}
                You have already written the exam
            {% else %}
                CHOOSE THE CORRECT ANSWER
            {% endif %}

        </h1>
    </div>
    <input type="hidden" name="exam" value={{ object.id }}>
    {% for question in object.question_set.all|shuffle %}
        <article class="media content-section">
            <div class="media-body">
                <div class="article-metadata">
                    {{ forloop.counter }} &emsp; {{ question }}
                    {% comment %}
                    <!-- <small class="text-muted">{{ exam.start_date|date:"F d, Y"}}</small> -->
                    {% endcomment %}
                </div>
                    {% for value in question.get_fields %}
                        <input type="radio" id="{{ forloop.parentloop.counter }}{{ forloop.counter }}" name="{{ question.id }}" value="{{ value }}" required="True">
                        <label for="{{ forloop.parentloop.counter }}{{ forloop.counter }}" > {{ value }} </label> <br>
                    {% endfor %}
            </div>
        </article>
    {% endfor %}
    {% if has_written %}
    {% else %}
    <div class="row spacer">
        <div class="col-4 offset-2">
            <button type="submit" class="btn btn-block btn-primary">Submit</button>
        </div>
    </div>
    {% endif %}
</form>

来源:https://stackoverflow.com/questions/60650878/how-to-stop-init-of-a-class-based-view-executing-twice-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!