Please have a look at this code:
models:
class Activity(models.Model):
actor = models.ForeignKey(User)
action = models.CharField(max_length=100)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
pub_date = models.DateTimeField(auto_now_add=True, auto_now=False)
class Meta:
verbose_name = 'Activity'
verbose_name_plural = 'Activities'
ordering = ['-pub_date']
def __unicode__(self):
return ("%s %s") % (self.actor.username, self.action)
def get_rendered_html(self):
template_name = '%s_activity.html' %(self.content_type.name)
return render_to_string(template_name, {
'object':self.content_object,
'actor':self.actor,
'action':self.action,
})
template:
<div class="user_activity">
<p>{{ actor.username }} {{ action }} {{ object.content_object.user.username }} status</p>
<p>{{ object.content_object.body }}</p>
<p>{{ object.content_object.pub_date }}</p>
{% if object.content_object.image %}
<div class="activity_img_wrapper">
<p><img src="/media/{{ object.content_object.image }}"/></p>
</div>
{% endif %}
</div>
Question
How do I get the requested user's username for the above template (request.user). I did like this, but it didn't help :
<div class="user_activity">
<p>
{% if user.username == actor.username %}
You
{% else %}
{{ actor.username }}
{% endif %}
{{ action }}
{% if user.username == object.content_object.user.username %}
Your
{% else %}
{{ object.content_object.user.username }}
{% endif %}
status
</p>
<p>{{ object.content_object.body }}</p>
<p>{{ object.content_object.pub_date }}</p>
{% if object.content_object.image %}
<div class="activity_img_wrapper">
<p><img src="/media/{{ object.content_object.image }}"/></p>
</div>
{% endif %}
</div>
Please help me how to do it. I would really be grateful for your help. Thank you.
There is no RequestContext object available in the get_rendered_html() method so you can't pass it as a context_instance argument of the render_to_string(). This is why the user variable is not available in the template.
You should pass the User instance to get_rendered_html() method and propagate it to the template:
def get_rendered_html(self, user=None):
template_name = '%s_activity.html' %(self.content_type.name)
return render_to_string(template_name, {
'object':self.content_object,
'actor':self.actor,
'action':self.action,
'user':user,
})
If you want to call this method from other template then the best option is to use custom template tag:
# app/templatetags/activity_tags.py
# and don't forget to create empty app/templatetags/__init__.py :-)
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
#register.simple_tag(takes_context=True)
def render_activity(context, activity):
user = context['user']
html = activity.get_rendered_html(user)
return mark_safe(html)
And then load and use this tag library in your template:
{% load activity_tags %}
...
{% render_activity activity %}
Related
I am trying to find out why some data from my views.py are not showing up. Here's my code
views.py
def user(request, user_id):
profile = get_object_or_404(User, pk=user_id)
rnk = Ranks.objects.all()
context = {
'profile' : profile,
'rnk' : rnk,
}
return render(request, 'user/user.html', context)
I am trying to show, for example the rank_name from my model and I use {{rnk.rank_name}} in the HTML template but it's not showing up.
On the other hand, data from profile like {{profile.user_name}} are showing up.
Note that rnk and profile are from this model:
class Ranks(models.Model):
rank_name = models.CharField(max_length=300)
description = models.TextField(blank=True)
def __str__(self):
return self.br_rank_name
class User(models.Model):
b_rank = models.ForeignKey(Ranks, on_delete=models.DO_NOTHING)
name = models.CharField(max_length=20)
link = models.URLField(max_length=100)
weekly = models.BooleanField(default=False)
biweekly = models.BooleanField(default=False)
def __str__(self):
return self.name
Here's my template
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h5>{{profile.user_name}}</h5><!--This shows up-->
<p>{{rnk.rank_name}}</p>
<p>{{profile.weekly}}</p>
<span class="icon-desc">{{rnk.rank_points}} points</span>
{% endblock %}
That's because the rnk passed to the template is a queryset and includes multiple objects. So you need to iterate rnk using for and try to show the details for each one in your template.
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h5>{{ profile.user_name }}</h5>
<p>{{ profile.weekly }}</p>
{% for rank in rnk %}
<p>{{ rank.rank_name }}</p>
<span class="icon-desc">{{ rank.rank_points }} points</span>
<img src="{{ rank.br_photo.url }}" height="150" alt="">
{% endfor %}
{% endblock %}
I create a financial manager and I need the user to change the account activity (indicate an active account or not), but when I send the form for change, then the model attribute does not change and always remains TRUE
I also tried to do this through a copy of the Account, but it was also not a result of the outcome
Account.objects.get(user=self.request.user, id=id).is_active = False
models.py
class Account(models.Model):
type_of_currency = models.CharField(max_length=20)
user = models.ForeignKey(get_user_model(), blank=True,
related_name='user_account',
on_delete=models.CASCADE)
count = models.DecimalField(max_digits=12, decimal_places=2, blank=True)
created = models.DateTimeField(default=datetime.datetime.now)
is_active = models.BooleanField()
def __str__(self):
return f'{self.type_of_currency} - {self.count}'
views.py
class AccountDetailView(DetailView, UpdateView):
model = Account
form_class = AccountCreateForm
template_name = 'account_detail.html'
def post(self, request, *args, **kwargs):
id = self.request.POST['accountid']
self.request.user.user_account.get(id=6).is_active = False
print(self.request.user.user_account.get(
id=id).is_active) # always True why?
return redirect('/counts/' + id)
template
{% extends 'base.html' %}
{% block content %}
<div class="col-sm-5">
<h1>account: {{ account.id }}</h1>
<p><strong>Author:</strong> {{ account.user }}</p> <!-- author detail link not yet defined -->
<p><strong>Type:</strong> {{ account.type_of_currency }}</p>
<p><strong>count:</strong> {{ account.count }}</p>
<p><strong>IsCreated:</strong> {{ account.created }}</p>
<p><strong>IsActive:</strong>{{ account.is_active }}</p>
<a class="btn btn-outline-primary"
href="{% url 'account-list' %}">Back</a>
{% if account.is_active %}
<form method="post">
{% csrf_token %}
<input type="hidden" value="{{ account.id }}" name="accountid">
<button type="submit" class="btn btn-outline-danger">Deactivate</button>
</form>
{% else %}
<form method="post">
{% csrf_token %}
<button type="submit" class="btn btn-outline-success">Activate</button>
</form>
{% endif %}
</div>
{% endblock %}
In the post method DetailViews, I expect that after the button is pressed, user activity will change, but the result is always True
You're never commiting change to DB.
Also, I wouldn't use the following syntax: self.request.user.user_account.get(id=6).is_active = False
You can try: self.request.user.user_acocount.filter(id=6).update(is_active=False)
But, if you're dead set on using .get():
user_acc = self.request.user.user_account.get(id=6)
user_acc.is_active = False
user_acc.save()
I want to know how to upload and display the image.
I do have the classes in views.py.
class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Article
fields = ('title', 'body', 'image', 'source_url')
template_name = 'article_edit.html'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class ArticleCreateView(LoginRequiredMixin, CreateView):
model = Article
template_name = 'article_new.html'
fields = ('title', 'body', 'image', 'source_url')
login_url = 'login'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
And the relevant classes in the models.py are like as follow.
class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(
upload_to='media/', null=True, blank=True)
source_url = models.URLField(blank=True, null=True, max_length=300)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article_detail', args=[str(self.id)])
class Comment(models.Model):
article = models.ForeignKey(Article,
on_delete=models.CASCADE, related_name='comments', )
comment = models.CharField(max_length=140)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE),
def __str__(self):
return self.comment
def get_absolute_url(self):
return reverse('article_list')
The article_list.html file is:
{% extends 'base.html' %}
{% load static %}
{% block title %}Articles{% endblock title %}
{% block content %}
{% for article in object_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ article.title }}</span> ·
<span class="text-muted">by {{ article.author }} |
{{ article.date }}</span>
</div>
<div class="card-body">
{{ article.body|linebreaks}}
{% comment %} {% if article.image.url|length > 0 %}
<img src="{{ article.image.url }}" width="200px">
{% else %}
<img src="{% static '/media/mrDoctor.jpg' %}" width="200px" />
{% endif %} {% endcomment %}
<img src="{% static 'articles/mrDoctor.jpg' %}" alt="Image" width="200px" />
Link
Edit
Delete
</div>
<div class="card-footer">
{% for comment in article.comments.all %}
<p>
<span class="font-weight-bold">
{{ comment.author }} ·
</span>
{{ comment }}
</p>
{% endfor %}
</div>
</div>
<br />
{% endfor %}
{% endblock content %}
The user can select the image file from the form.
I can not display the image selected from the input form shown above on the screen shot. I want to display the images dynamically, i.e., when the user choose the image file from the input form. I know I should change the part:{% static '/media/mrDoctor.jpg' %}. When I tried the commented part of article_list.html, i.e., {% if article.image.url|length > 0 %}, it did not work. I will appreciate it if you help me to fix the problem. Many thanks.
After reflecting #Hybrid suggestions, I was able to show the image on the first article but the second and the third one show only the file names.
You can do this by using JavaScript to detect when a user selects an image, and then replacing an <img /> tags src dynamically.
Example code:
<img id="image" />
<input id="files" type="file" />
<script>
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
</script>
To product page of my project I need to add paginator. I did according to the Django Documentation but I have the following error:
object of type 'InsuranceProducts' has no len()
Here is the my views.py:
def farmer_types(request, type_id):
product_areas = InsuranceProducts.objects.filter(product_type="Фермерам")
product_types = get_object_or_404(InsuranceProducts, id=type_id)
paginator = Paginator(product_types, 6)
page = request.GET.get('page')
types = paginator.get_page(page)
context = {'product_types': product_types,
'product_areas': product_areas,
'types': types}
return render(request, 'insurance_products/farmer/farmer_types.html', context)
Here is the my models.py:
class InsuranceProducts(models.Model):
product_area = models.CharField(max_length=100)
product_description = models.TextField()
product_type = models.CharField(max_length=50)
def __str__(self):
return "{}-{}".format(self.product_area, self.product_type)
class ProductType(models.Model):
product_area = models.ForeignKey(InsuranceProducts, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
description = models.TextField()
body = HTMLField('Content')
def __str__(self):
return "{} - {}".format(self.product_area, self.title)
Here is the code from the template:
{% for product in types.producttype_set.all %}
<div class="btmspace-80">
<h3>{{ product.title|upper }}</h3>
<img class="imgr borderedbox inspace-5" src="{% static 'img/imgr.gif' %}" alt="">
<p>
{{ product.description|upper }}
</p>
<p>
Подробно вы можете узнать о новости здесь</a>
</p>
</div>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if types.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ types.number }} of {{ types.paginator.num_pages }}.
</span>
{% if types.has_next %}
next
last »
{% endif %}
</span>
</div>
<!-- ################################################################################################ -->
</div>
I did the everything as it is given in the Docs.
Why is product_types plural if you are using get_object_or_404, which returns only one object?
You're doing the pagination right, but doing the query wrong. If you change paginator = Paginator(product_types, 6) to paginator = Paginator(product_areas, 6), you will see that it works perfectly fine.
You should read the documentation on how to do queries, and understand the relationships between models.
need your assistance in figuring out what is wrong with a form in my django app,i have a tab section in my app that has three tabs (lesson,workbook,answer).The work flow is that a user goes through some lesson content then clicks on a "take exercise" button which leads him to the workbook tab.Here i have questions which can either be multiple choice question or easy question depending on the lesson, after completing exercise a user submits the question and he transitions to the answers tab where his submitted answer is displayed in addition to the expected answer if he was wrong.My problem is that when the submit button is clicked the answers are not submitted and hence no user answers are displayed in the answer tab.
Here is the html code
<div class="tabs present-addition">
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li {% if active_tab == "lesson" %}class="active"{% endif %}>Lesson Content</li>
<li {% if active_tab == "workbook" %}class="active"{% endif %}>Workbook</li>
<li {% if active_tab == "answers" %}class="active"{% endif %}>Answers</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>View Example</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 -->
Here is the 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}
)))
Here is the 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"))
Here is the forms.py
class LessonExerciseForm(forms.ModelForm):
model = [MultiChoiceQuestion, ExerciseSubmission, EssayQuestion]
fields = '__all__'
I had very similar problem while dealing with different issue. But I think your problem is the same.
link to post
Basically the problem was the html code. I would suggest that you verify your generated html code in browser and check if the form tags are closed properly. It might be the case that form tags are closed earlier than your data is coming later in html and it wouldn't be submitted. Check generated html.