I can't figure out how to create a page with multiple Questions and their Answers. The main thing is that I want User to take a Quiz which contain's multiple Questions and Questions have multiple Answers.
The first thing I want is to render at least one Question with it's answers, and if it works, then figure out how to render multiple questions on one page (whole Quiz), but it doesn't render anything except base.html.
But when I try to print question_form in a view, it returns:
Exception Type: TypeError at /language-tests/question
Exception Value:'Answer' object is not iterable
Do you have any ideas, what's wrong?
question.html
{% extends 'base.html' %}
{% block content %}
{{ question_form }}
{% endblock %}
FORM
class QuestionForm(forms.Form):
def __init__(self, question, *args, **kwargs):
super(QuestionForm, self).__init__(*args, **kwargs)
choice_list = [x for x in question.get_answers_list()]
self.fields["answers"] = forms.ChoiceField(choices=choice_list,
widget=forms.RadioSelect)
VIEW - simple view just for see if the question form can be rendered
def question(request):
question_form = forms.QuestionForm(question=models.Question.objects.get(pk=1))
return render(request,'question.html',context={'question_form':question_form})
MODELS
class LanguageQuiz(models.Model):
name = models.CharField(max_length=40)
language = models.OneToOneField(sfl_models.Language)
max_questions = models.IntegerField()
def __str__(self):
return '{} test'.format(self.name)
def __unicode__(self):
return self.__str__()
class Question(models.Model):
language_quiz = models.ForeignKey(LanguageQuiz,related_name='questions')
text = models.TextField()
def get_answers_list(self):
return self.answers.all()
class Answer(models.Model):
question = models.ForeignKey(Question,related_name='answers')
text = models.TextField()
correct = models.BooleanField()
A Django form field choices argument should be an iterable of 2-tuples, see https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices
You probably want to say something like
choice_list = [(x.id, x.text) for x in question.get_answers_list()]
Your exception 'Answer' object is not iterable is because Django is trying to iterate over this 2-tuple, but finding instead the Answer object.
Related
In Django, how can I sort the results of a method on my model?
class Flashcard(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
question = models.TextField()
answer = models.TextField()
difficulty = models.FloatField(default=2.5)
objects = FlashcardManager()
def __str__(self):
return self.question
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile')
bio = models.TextField(max_length=500,null=True, default='',blank=True)
def __str__(self):
return f'{self.user.username} Profile'
def avg_diff_user(self):
avg_diff = Flashcard.objects.filter(owner = self.user).aggregate(Avg('difficulty'))['difficulty__avg']
return avg_diff
So with avg_diff_user, I get each user's average difficulty rating. Which I can then use in my leaderboard template as follows:
<ol>
{% for user in leaderboard_list %}
<li>{{user.username}}: {{user.profile.avg_diff_user|floatformat:2}}</li>
{% endfor %}
</ol>
The results show, but it's not sorted - how can I sort by avg_diff_user? I've read many similar questions on SO, but to no avail. I've tried a different method on my model:
def avg_diff_sorted(self):
avg_diff_sorted = Flashcard.objects.all().annotate(get_avg_diff_user=Avg(Flashcard('difficulty'))['difficulty__avg'].order_by(get_avg_diff_user))
return avg_diff_sorted
Which I don't think is right and didn't return any results in my template. I also tried the following, as suggested in https://stackoverflow.com/a/930894/13290801, which didn't work for me:
def avg_diff_sorted(self):
avg_diff_sorted = sorted(Flashcard.objects.all(), key = lambda p: p.avg_diff)
return avg_diff_sorted
My views:
class LeaderboardView(ListView):
model = User
template_name = 'accounts/leaderboard.html'
context_object_name = 'leaderboard_list'
def get_queryset(self):
return self.model.objects.all()
something like:
leaderboard_list = User.objects.all().annotate(avg_score=Avg('flashcard__difficulty').order_by('-avg_score')
will sort you the users by their average score.
I don't use ListView that often by if you just used a standard view like:
def LeaderboardView(request):
leaderboard_list = ...
context = {'leaderboard_list':leaderboard_list}
return render(request, 'accounts/leaderboard.html', context)
In your html you could do the same:
{% for user in leaderboard_list %}
...
{% endfor %}
I have the following problem. I need to get the information of the question based on the questionitem.question_id
I have the following files.
# models.py
class Question(models.Model):
qtype_id = models.ForeignKey(QuestionType, on_delete=models.CASCADE )
q_discription = models.CharField(max_length=150)
def __iter__(self):
return self.pk
class QuestionItem(models.Model):
exam_id = models.ForeignKey(Exam, on_delete=models.CASCADE)
question_id = models.ForeignKey(Question, on_delete=models.CASCADE)
question_pontuation = models.FloatField(default=0.0)
def __iter__(self):
return self.pk
# views.py
def ExamDetail(request, exam_id):
exam = get_object_or_404(Exam, pk=exam_id)
questionitems = QuestionItem.objects.filter(exam_id= exam_id).values_list('id', flat=True)
questions = Question.objects.filter(pk__in=questionitems)
context = {
'exam': exam,
'questions': questions,
'questionitem': questionitems,
}
return render(request, 'evaluation/exam_detail.html' , context)
And now on exam_detail.html i have something like this:
{% for questionitem in exam.questionitem_set.all %}
Question {{questionitem.id}}</a>: {{question.q_discription}}
{% endfor%}
but nothing shows, and i need to show the description of the question in questionitem.question_id, and i cant change the models.py.
Probably, you have problem in the way, you are accessing queryset in loop. Change code to :-
{% for questionitem in exam.questionitem_set.all %}
Question {{questionitem.id}}</a>: {{questionitem.question_id.q_discription}}
{% endfor%}
q_discription is the part of Question class, which is accessible using question_id on questionitem instance, that you receive in the loop.
I use the form Bannerform to create new Banner object trough the add_banner views (and template). I use the class Options to definite which affiliation objects to permit in the form Bannerform (affiliation field).
I'm trying to pass choices from the views to the form but it give me ValueError: too many values to unpack (expected 2)
My code worked when new_affiliation was a ForeignKey but now I need more values. I think I must definite 'choices' in the views or I will have problem on the first migration (it appear to call the database tables from the models.py but not from the views.py, so if I put Options.objects.get(id=1) on the models.py it give error because the tables don't exist yet).
My form.py:
from django import forms
from core.models import Options, Banner, Affiliation #somethings other
class BannerForm(forms.ModelForm):
name = forms.CharField(max_length=32)
affiliation = forms.ChoiceField('choices')
#affiliation = forms.ModelChoiceField('choices') #same error
class Meta:
model = Banner
exclude = (#some fields)
My models.py:
from django.db import models
from django.contrib.auth.models import User
from django import forms
class Options(models.Model):
new_affiliation = models.ManyToManyField('Affiliation')
#new_affiliation = models.ForeignKey('Affiliation') #this worked (with some changes in views)
class Affiliation(models.Model):
name = models.CharField(max_length=32, unique=True)
class Banner(models.Model):
name = models.CharField(max_length=32, unique=True)
affiliation = models.ForeignKey(Affiliation)
My views.py:
def add_banner(request):
if request.method == 'POST':
#some code here
else:
options = Options.objects.get(id=1)
print(options.new_affiliation.all()) #controll
choices = options.new_affiliation.all()
print(choices) #controll
form = BannerForm(choices, initial={
#some code regarding other fields
})
return render(request, 'core/add_banner.html', {'form': form})
My add_banner.html:
<form role="form" id="banner_form" enctype="multipart/form-data "method="post" action="../add_banner/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.label }}
{{ field }}
{{ field.help_text }}
<br />
{% endfor %}
Any help will be apreciated.
Updated. I changed only views.py:
def add_banner(request):
if request.method == 'POST':
#some code here
else:
options = Options.objects.get(id=1)
print(options.new_affiliation.all()) #controll
choices = tuple(options.new_affiliation.all())
print(choices) #controll
form = BannerForm(choices, initial={
#some code regarding other fields
})
return render(request, 'core/add_banner.html', {'form': form})
But still give error.
Update 2. If I pass choices directly from form.py it works:
My views.py:
def add_banner(request):
if request.method == 'POST':
#some code here
else:
form = BannerForm(request.POST or None, initial={
#some code regarding other fields
})
return render(request, 'core/add_banner.html', {'form': form})
My forms.py:
class BannerForm(forms.ModelForm):
options = Options.objects.get(id=1)
choices = options.new_affiliation.all()
name = forms.CharField(max_length=32)
affiliation = forms.ModelChoiceField(choices)
Unluckly this give problems on the first migration (see above).
I'm trying to pass choices using some init method...
My forms.py:
class BannerForm(forms.ModelForm):
name = forms.CharField(max_length=32)
affiliation = forms.ModelChoiceField(choices)
def __init__(self, *args, **kwargs):
options = Options.objects.get(id=1)
choices = options.new_affiliation.all()
#choices = kwargs.pop('choices')
super(RegentForm, self).__init__(*args, **kwargs)
self.fields['affiliation'] = choices
but it say that choices is not definite
From what I can see here, it looks like you are getting an error "too many values to unpack" because you are not sending "choices" as the correct type. A ChoiceField takes choices only as a tuple, as seen in the documentation for models. If you are looking to define choices based on a QuerySet, you'll have to convert it into a tuple which can be interpreted as valid "choices". In one of my projects for example, I needed to prepare a set of years as a tuple so that I could allow users to select from a list of pre-determined years. I specified the following function to do this:
def years():
response = []
now = datetime.utcnow()
for i in range(1900, now.year + 1):
response.append([i, str(i)])
return tuple(response)
Since tuples are meant to be immutable, it usually isn't a good idea to cast them, just based on principle. However, in this case it seems necessary as a measure to declare that you are okay with the possible variability with these statements.
In your specific situation, you might consider doing something like this:
choices = tuple(options.new_affiliation.all().values())
I have not tested this code, and I frankly am not completely familiar with your project and may be mistaken in some part of this response. As a result, it may require further tweaking, but give it a try. Based on your error, this is definitely where the program is breaking currently. Update here if you make any progress.
Done!
My form.py:
class BannerForm(forms.ModelForm):
name = forms.CharField(max_length=32, label='Nome')
def __init__(self, *args, **kwargs):
options = Options.objects.get(id=1)
choices = options.new_affiliation.all()
super(BannerForm, self).__init__(*args, **kwargs)
self.fields['affiliation'] = forms.ModelChoiceField(choices)
self.fields['affiliation'].initial = choices
class Meta:
model = Banner
My views.py:
def add_banner(request):
if request.method == 'POST':
#some code here
else:
form = BannerForm(request.POST or None, initial={
#some code here
})
return render(request, 'core/add_banner.html', {'form': form})
Thank you
I am trying to display only objects, which are not older then 4 days. I know I can use a filter:
new = Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4))
but I really want to use a modal method for exercise.
The method is defined in model Book and is called published_recetnly.
So my question is how to call a modal method in views.py?
This is my current code:
views.py
def index(request):
new = Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4))
return render_to_response('books/index.html', {'new':new}, context_instance=RequestContext(request))
index.html
{% if book in new %}
{{ book.title }}
{% endif %}
models.py
class Book(models.Model)
pub_date = models.DateTimeField('date published')
def published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=4) <= self.pub_date <= now
Maybe you should use a manager in this case. It's more clear and you can use it to retrieve all published recently books.
from .managers import BookManager
class Book(models.Model)
pub_date = models.DateTimeField('date published')
objects = BookManager()
Set like this your managers file:
class BookManager(models.Manager):
def published_recently(self,):
return Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4))
And now, you can filter more clearly in your views file.
Books.objects.published_recently()
Hi i want to display a count of answers to my question model
my model:
class Question(models.Model):
text = models.TextField()
title = models.CharField(max_length=200)
date = models.DateTimeField(default=datetime.datetime.now)
author = models.ForeignKey(CustomUser)
tags = models.ManyToManyField(Tags)
def __str__(self):
return self.title
class Answer(models.Model):
text = models.TextField()
date = models.DateTimeField(default=datetime.datetime.now)
likes = models.IntegerField(default=0)
author = models.ForeignKey(CustomUser)
question = models.ForeignKey(Question)
my view:
def all_questions(request):
questions = Question.objects.all()
answers = Answer.objects.filter(question_id=questions).count()
return render(request, 'all_questions.html', {
'questions':questions, 'answers':answers })
Right now view displays count of all answers. How can i filter it by the Question model?
You can use .annotate() to get the count of answers associated with each question.
from django.db.models import Count
questions = Question.objects.annotate(number_of_answers=Count('answer')) # annotate the queryset
By doing this, each question object will have an extra attribute number_of_answers having the value of number of answers associated to each question.
questions[0].number_of_answers # access the number of answers associated with a question using 'number_of_answers' attribute
Final Code:
from django.db.models import Count
def all_questions(request):
questions = Question.objects.annotate(number_of_answers=Count('answer'))
return render(request, 'all_questions.html', {
'questions':questions})
In your template, then you can do something like:
{% for question in questions %}
{{question.number_of_answers}} # displays the number of answers associated with this question
See the docs
You can annotate the Query, like:
from django.db.models import Count
questions = Question.objects.annotate(num_answer=Count('answer'))
but, refactor the code to this.
Remove the count of answers:
def all_questions(request):
questions = Question.objects.all()
return render(request, 'all_questions.html', {'questions':questions })
Now, in all_question.html. Just use :
{% for question in questions %}
Title: {{question.title}}
Count Answers: {{question.answer_set.all|length}}
{% for answer in question.answer_set.all %}
{{answer.text}}
{% endfor %}
{% endfor %}
It is more efficienty.