在我的django应用程序中需要帮助找出表单有什么问题,我的应用程序中有一个标签部分,有三个标签(课程,工作簿,答案)。工作流程是用户经历一些课程内容然后点击"参加练习"按钮导致他进入工作簿选项卡。这里有问题,可以是多项选择题或简单问题,取决于课程,完成练习后,用户提交问题,然后他转到答案选项卡,其中提交的答案显示在如果他错了,那么除了预期的答案。我的问题是,当点击提交按钮时,答案没有提交,因此答案标签中没有显示用户答案。
这是html代码
<div class="tabs present-addition">
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li {% if active_tab == "lesson" %}class="active"{% endif %}><a href="#lesson" data-toggle="tab">Lesson Content</a></li>
<li {% if active_tab == "workbook" %}class="active"{% endif %}><a href="#workbook" data-toggle="tab">Workbook</a></li>
<li {% if active_tab == "answers" %}class="active"{% endif %}><a href="#answers" data-toggle="tab">Answers</a></li>
</ul>
{% if messages %}
<div>{{ message }}</div>
<!--<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>-->
{% endif %}
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="lesson">
<p>{{ lesson.content|safe }}</p>
<!--<p><a href="#" data-toggle="modal" data-target="#modalStyle2">View Example</a></p>-->
{% if lesson.instructions_before %}
<h3>Instructions</h3>
<p>{{ lesson.instructions_before|safe }}</p>
{% endif %}
<div class="btn-container btn-container-info" id="wkbck">
<a class="btn btn-info btn--minimal btn-lg-bordered btn-inverse" href="#" data-toggle="tab" data-target="#workbook" >Take Exercise</a>
</div>
</div>
<div class="tab-pane" id="workbook">
{% if lesson.get_exercises %}
{% for exercise in lesson.get_exercises %}
<h4>{{ exercise.title }}</h4>
<form method="post" action="{% url 'exercise_submit' lesson.id exercise.id %}" class="contact" style="text-align:left;">
{% csrf_token %}
<input type="hidden" id="exercise_id" name="exercise_id" value="{{ exercise.id }}">
{% for question in exercise.question_set.all %}
<h6>{{ question.title }}</h6>
{% for answer in question.num_of_expected_answers|get_range %}
{{ forloop.counter }}: <input type="text" name="qu-{{ question.id }}-{{ forloop.counter }}" id="answer-{{ question.id }}-{{ forloop.counter }}" class="contact__field" style="width: 50%;" required /></br>
{% endfor %}
{% endfor %}
{% for mcquestion in exercise.multichoicequestion_set.all %}
<h6>{{ mcquestion.title }}</h6>
<div class="checkbox">
{% for option in mcquestion.multichoicequestionoption_set.all %}
{% with forloop.counter as curr_counter %}
<input type="checkbox" id="mcq-{{ mcquestion.id }}-{{ curr_counter }}" name="mcq-{{ mcquestion.id }}-{{ curr_counter }}" value="{{ option.content }}" >
<label for="mcq-{{ mcquestion.id }}-{{ curr_counter }}">{{ option.content }}</label>
{% endwith %}
{% endfor %}
</div>
</br>
{% endfor %}
{% for essay_question in exercise.essayquestion_set.all %}
<h6>{{ essay_question.title }}</h6>
<div class="modal-body">
<textarea rows="6" cols="50" class="contact__field contact__area" style="width: 50%;" name="eq-{{ essay_question.id }}" id="eq-{{ essay_question.id }}" placeholder="Type your answer here" required></textarea>
</div>
</br>
{% endfor %}
<div class="btn-container btn-container-info">
<button type="sumbit" class="btn btn-info btn--minimal btn-lg-bordered btn-inverse" data-toggle="tab" data-target="#answers" >Submit</button>
</div>
</form>
{% endfor %}
{% endif %}
<p>
<!--<div class="btn-container btn-container-info">
<a class="btn btn-info btn--minimal btn-lg-bordered btn-inverse" href="#"> Submit </a>
</div>-->
</p>
</div>
<div class="tab-pane" id="answers">
<h4>Exercise Answers</h3>
<!-- Display normal question answers -->
{% if questions and answers %}
{% for question in questions %}
<h6><b>{{ question.title }}</b></h6>
{% if answers %}
<ol>
{% for answer in answers %}
{% if answer.question.id == question.id %}
<li>{{ answer.answer }}</li>
{% endif %}
{% endfor %}
</ol>
{% endif %}
<h6>Expected Answer</h6>
<p>{{ question.expected_answer|safe }}</p>
<hr/>
{% endfor %}
{% endif %}
<!-- Display multichoice question answers -->
{% if multichoice_questions and mc_answers %}
{% for mc_question in multichoice_questions %}
<h6><b>{{ mc_question.title }}</b></h6>
{% if mc_answers %}
{% for mc_answer in mc_answers %}
{% if mc_answer.question.id == mc_question.id %}
<p>{{ mc_answer.selected_choice }}</p>
{% endif %}
{% endfor %}
{% endif %}
<h6>Expected Answer</h6>
<p>{{ mc_question.expected_answer|safe }}</p>
<hr/>
{% endfor %}
{% endif %}
<!-- Display essay question answers -->
{% if essay_questions and eq_answers %}
{% for es_question in essay_questions %}
<h6><b>{{ es_question.title }}</b></h6>
{% if eq_answers %}
{% for eq_answer in eq_answers %}
{% if eq_answer.question.id == es_question.id %}
<p>{{ eq_answer.answer }}</p>
{% endif %}
{% endfor %}
{% endif %}
<h6>Expected Answer</h6>
<p>{{ es_question.expected_answer|safe }}</p>
<hr/>
{% endfor %}
{% endif %}
<!-- This exercise has not been answered -->
{% if not answers and not mc_answers and not eq_answers %}
<p>Will be revealed after submitting your work.</p>
{% endif %}
<!-- Show next lesson button if available -->
{% if answers or mc_answers or eq_answers %}
{% if lesson.next_lesson %}
<p>
<div class="btn-container btn-container-warning">
<a class="btn btn-warning btn--minimal btn-lg-bordered btn-inverse" href="{% url 'learn_lesson' lesson.next_lesson.module.course.slug lesson.next_lesson.module.slug lesson.next_lesson.slug %}">Next Lesson</a>
</div>
</p>
{% endif %}
{% endif %}
</div>
</div>
</div>
<!-- end tabs -->
这是view.py
def lesson_exercise_posted(request, lesson_id, exercise_id):
if request.method == 'POST':
form = LessonExerciseForm(request.POST)
lesson = Lesson.objects.get(pk=lesson_id)
exercise = Exercise.objects.get(pk=exercise_id)
exercise_submission, created = ExerciseSubmission.objects.get_or_create(
student=request.user,
#lesson=lesson,
exercise=exercise)
if created:
for key in request.POST.iterkeys():
value = request.POST.get(key)
print("{0}:::{1}".format(key, value))
if value:
# Get Link Questions; Can be more than one
if key.startswith('qu'):
prefix, question_id, question_counter = key.split('-')
qu_question = Question.objects.get(pk=question_id)
user_answer = UserAnswer(student=request.user,
question=qu_question,
answer=value.strip(),
exercise_submission=exercise_submission)
user_answer.save()
# Get Multichoice Questions
if key.startswith('mcq'):
prefix, question_id, choice_counter = key.split('-')
mc_question = MultiChoiceQuestion.objects.get(pk=question_id)
mc_option_selected = MultiChoiceQuestionOption.objects.get(question=mc_question, content=value.strip())
mc_answer = MultiChoiceUserSubmittedAnswer(
student=request.user,
question=mc_question,
selected_choice=mc_option_selected,
exercise_submission=exercise_submission)
mc_answer.save()
# Get Essay Questions
if key.startswith('eq'):
prefix, question_id = key.split('-')
essay_question = EssayQuestion.objects.get(pk=question_id)
try:
essay_answer = EssayUserAnswer.objects.get(student=request.user, question=essay_question)
except EssayUserAnswer.DoesNotExist:
essay_answer = EssayUserAnswer(student=request.user,
question=essay_question,
answer=value.strip(),
exercise_submission=exercise_submission)
essay_answer.save()
# Update the user progress
progress = StudentLessonProgress.objects.get(student=request.user, lesson=lesson)
progress.status = COMPLETED
progress.done_percent = 100 # Incrementing percentage at this stage to make it 100
progress.save()
messages.success(request, "Thank you! Your answer submission has been saved. Click on the Answers tab to reveal the correct answers.")
else:
form = LessonExerciseForm()
messages.success(request, "Thank you! Your answer submission was NOT saved because you had previously done this exercise.")
return HttpResponseRedirect( '{0}#answers'.format(reverse('learn_lesson',
kwargs={
'form':form,
'course_slug':lesson.module.course.slug,
'module_slug':lesson.module.slug,
'lesson_slug':lesson.slug}
)))
这是models.py
class Exercise(models.Model):
title = models.CharField(max_length=256, null=True)
def __unicode__(self):
return self.title
class ExerciseSubmission(models.Model):
""" Data Model representing a student's exercise Submission. """
student = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='The Student', related_name='exercise_submissions')
exercise = models.ForeignKey(Exercise, verbose_name=_("Exercise"))
#lesson = get_model('jm_lms.apps.courses.models', 'Lesson') #models.ForeignKey(Lesson, verbose_name='Lesson')
date = models.DateTimeField(editable=False, auto_now_add=True)
class Meta:
verbose_name = _("Exercise Submission")
verbose_name_plural = _("Exercise Submissions")
class BaseQuestion(models.Model):
exercise = models.ForeignKey(Exercise, verbose_name=_("Exercise"))
title = models.TextField(verbose_name="Topic Box", blank=True, null=True)
expected_answer = models.TextField(verbose_name="Expected Answer", blank=True, null=True, help_text=_("How the learner should answer the question. Shown after the question has been answered."))
class Meta:
abstract = True
def __unicode__(self):
return self.title
class Question(BaseQuestion):
num_of_expected_answers = models.IntegerField(default=1, verbose_name=_("Number of expected answers"))
class Meta:
verbose_name = _("List Question")
verbose_name_plural = _("List Questions")
class UserAnswer(models.Model):
"""
Response given by a user
"""
student = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='The Student', related_name='exercise_answers')
question = models.ForeignKey(Question, verbose_name=_("Question"))
answer = models.CharField(max_length=256, null=True)
answered_on = models.DateTimeField(auto_now_add=True, blank=True, null=True)
exercise_submission = models.ForeignKey(ExerciseSubmission, verbose_name=_("Exercise Submission"), blank=True, null=True)
# status = models.IntegerField(verbose_name="Answer Status", choices=USER_ANSWER_STATUS, default=NOT_PUBLISHED, help_text='Enable user answer reference in the next Lesson')
class Meta:
ordering = ("id",)
verbose_name = _("User Answer to List Question")
verbose_name_plural = _("User Answers to List Question")
def __unicode__(self):
return self.answer
class MultiChoiceQuestion(BaseQuestion):
class Meta:
verbose_name = _("Multiple Choice Question")
verbose_name_plural = _("Multiple Choice Questions")
def check_if_correct(self, guess):
answer = MultiChoiceQuestionOption.objects.get(id=guess)
if answer.correct is True:
return True
else:
return False
def get_answers(self):
return MultiChoiceQuestionOption.objects.filter(question=self)
def get_answers_list(self):
return [(answer.id, answer.content) for answer in MultiChoiceQuestionOption.objects.filter(question=self)]
class MultiChoiceQuestionOption(models.Model):
question = models.ForeignKey(MultiChoiceQuestion, verbose_name=_("Question"))
content = models.CharField(max_length=1000,
blank=False,
help_text=_("Enter the answer text that you want displayed"),
verbose_name=_("Answer Content"))
correct = models.BooleanField(blank=False,
default=False,
help_text=_("Is this a correct answer?"),
verbose_name=_("Correct"))
class Meta:
verbose_name = _("MultiChoice Option")
verbose_name_plural = _("MultiChoice Options")
def __unicode__(self):
return self.content
class MultiChoiceUserSubmittedAnswer(models.Model):
student = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='The Student', related_name='exercise_submitted_choice')
question = models.ForeignKey(MultiChoiceQuestion, verbose_name=_("Question"))
selected_choice = models.ForeignKey(MultiChoiceQuestionOption, verbose_name=_("Question"))
answered_on = models.DateTimeField(auto_now_add=True, blank=True, null=True)
exercise_submission = models.ForeignKey(ExerciseSubmission, verbose_name=_("Exercise Submission"), blank=True, null=True)
# status = models.IntegerField(verbose_name="Answer Status", choices=USER_ANSWER_STATUS, default=NOT_PUBLISHED, help_text='Enable user answer reference in the next Lesson')
class Meta:
verbose_name = _("MultiChoice Submitted User Answer")
verbose_name_plural = _("MultiChoice Submitted User Answers")
def __unicode__(self):
return self.selected_choice.content
class EssayQuestion(BaseQuestion):
class Meta:
verbose_name = _("Essay Question")
verbose_name_plural = _("Essay Questions")
class EssayUserAnswer(models.Model):
student = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='The Student', related_name='exercise_essay_answers')
question = models.ForeignKey(EssayQuestion, verbose_name=_("Question"))
answer = models.TextField(null=True, blank=True)
answered_on = models.DateTimeField(auto_now_add=True, blank=True, null=True)
exercise_submission = models.ForeignKey(ExerciseSubmission, verbose_name=_("Exercise Submission"), blank=True, null=True)
# status = models.IntegerField(verbose_name="Answer Status", choices=USER_ANSWER_STATUS, default=NOT_PUBLISHED, help_text='Enable user answer reference in the next Lesson')
# class TableExerciseQuestion(BaseQuestion):
# class Meta:
# verbose_name = _("Table Exercise Question")
# verbose_name_plural = _("Table Exercise Questions")
#
#
# class TableExercise(models.Model):
# """
# Model to enable lesson developer to add lesson exercise fields headers ,description e.t.c
# """
# question = models.ForeignKey(TableExerciseQuestion, verbose_name=_("Question"))
# field_name = models.CharField(max_length=200)
# field_occurrence = models.IntegerField(default=1, verbose_name=_("Number of expected fields"))
这是forms.py
class LessonExerciseForm(forms.ModelForm):
model = [MultiChoiceQuestion, ExerciseSubmission, EssayQuestion]
fields = '__all__'
答案 0 :(得分:0)
在处理不同问题时我遇到了类似的问题。但我认为你的问题是一样的。
基本上问题是html代码。我建议您在浏览器中验证生成的HTML代码,并检查表单标签是否正确关闭。可能会出现这样的情况:表单标签早于您的数据在html中出现时就会关闭,并且不会提交。检查生成的html。