I am trying to insert those value I got from radio buttons after the user as taken options. Then I want to insert it into another table which I will use to prepare the final result for the student. After I've taken all my values and created an insert query, I am getting this error.
models.py:
class Question(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='questions')
text = models.CharField('Question', max_length=500)
def __str__(self):
return self.text
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
text = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
def __str__(self):
return self.text
class TakenQuiz(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='taken_quizzes')
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='taken_course')
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='taken_question')
selected_choice = models.ForeignKey(Answer, on_delete=models.CASCADE, null=True)
marks_obtained = models.DecimalField('Marks Obtained', default=0, decimal_places=2, max_digits=6)
is_correct = models.BooleanField('Was this attempt correct?', default=False, null=False)
date = models.DateTimeField(auto_now_add=True)
views.py:
#login_required
#student_required
def take_exam(request, pk):
course = get_object_or_404(Course, pk=pk)
student = request.user.student
question = course.questions.filter()
#correct_answers = student.course_answers.filter(answer__question__quiz=course, answer__is_correct=True).count()
total_questions = course.questions.count()
choice = Answer.objects.filter()
marks_obtainable = Details.objects.get(course_id=course)
if request.method == 'POST':
question_pk = request.POST.getlist('question_pk')
choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk]
zipped = zip(question_pk, choice_pk)
for x, y in zipped:
correct_answers = Answer.objects.filter(question_id=x, is_correct=True).values('id').first()['id']
#print(type(correct_answers))
#print(choice_pk)
print(x, y, correct_answers)
print(x, y, correct_answers)
if int(y) == correct_answers:
print("correct") #using this to comfirm the the conditional statement above
z = TakenQuiz.objects.create(student=student, question=int(x), course=course, mark_obtained=marks_obtainable, is_correct=True)
z.save()
takenquiz = TakenQuiz()
takenquiz.student = student
takenquiz.question = x
takenquiz.course = course
takenquiz.selected_choice = y
takenquiz.marks_obtained = marks_obtainable
takenquiz.is_correct = True
takenquiz.save()
else:
print("Not correct")
z = TakenQuiz.objects.create(student=student, question=x, course=course, mark_obtained=marks_obtainable, is_correct=False)
z.save()
return render(request, 'classroom/students/take_exam_form.html', {
'course': course,
'question': question,
'course': course,
'total_questions': total_questions,
'choice': choice,
'marks_obtainable': marks_obtainable,
})
take_exam_form.html:
<form method="post" novalidate>
{% csrf_token %}
{% for questions in question %}
<input type="hidden" name="question_pk" value="{{ questions.pk }}">
<h3 class="text-info">{{ questions.text|safe }}</h3>
{% for choices in questions.answers.all %}
<input class="form-check-input" type="radio" name="choice_pk{{ questions.pk }}" id="choices-{{ forloop.counter }}" value="{{ choices.pk }}">
<label class="form-check-label" for="choices-{{ forloop.counter }}">
{{ choices.text|safe }}
</label>
{% endfor %}
{% endfor %}
<button type="submit" class="btn btn-primary">Submit Now →</button>
</form>
question_pk = request.POST.getlist('question_pk')
question_obj = Question.objects.filter(id=int(question_pk)
while save
takenquiz.question = question_obj
Related
So I am trying to set up a filter for my website and it is not working; It does not give me an error and the url updates like a query is being made but when I click "submit" it still shows all of the content in the page. I can't quite figure out what is wrong.
filters.py
import django_filters
from django_filters import DateFilter
from .models import *
class UserpostFilter(django_filters.FilterSet):
start_date = DateFilter(field_name = "date_published", lookup_expr='gte')
end_date = DateFilter(field_name = "date_published", lookup_expr='lte')
class Meta:
model = Userpost
fields = '__all__'
exclude = ['image', 'user', 'date_published']
models.py
class Userpost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
Year = models.CharField(max_length = 4)
Mileage = models.CharField(max_length = 8)
Make = models.CharField(max_length = 50)
Model = models.CharField(max_length = 50)
Price = models.DecimalField(max_digits=15, decimal_places=2)
email = models.EmailField()
date_published = models.DateField(default = timezone.now)
image = models.ImageField(null = True, blank = True, upload_to = r"C:\Users\gabri\Desktop\test\ecommerce\static\images")
def __str__(self):
return self.Year + " " + self.Make + " " + self.Model
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
views.py
def posts(request):
cars = Userpost.objects.all()
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
myFilter = UserpostFilter(request.GET, queryset = cars)
cars = myFilter.qs
context = {'cars':cars, 'cars_list':cars_list, "nums":nums, "myFilter":myFilter}
return render(request, 'store/userposts.html', context)
userposts.html
<div class = "row">
<div class="col">
<div class = "card card-body">
<form method="get">
{{myFilter.form}}
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
{% for car in cars_list %}
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
I would really appreciate if you guys could help me
EDIT
So I changed the order of the views to first filter and then paginate but it still does the same thing. I get no error, but display all the content from the page rather than the filtered ones.
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
cars = myFilter.qs
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)
The paginator should work on the cars not on the orignal queryset, since you are paginate over the filtered results
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
if not myFilter.is_valid():
raise ValidationError('filter is invalid')
cars = myFilter.qs
# This is the change
p = Paginator(cars, 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)
Models.py
class YearLevel(models.Model):
...
class Section(models.Model):
...
class Subject(models.Model):
...
class Student(models.Model):
first_name = models.CharField(max_length = 100, default = '')
last_name = models.CharField(max_length = 100, default = '')
year_level = models.OneToOneField(YearLevel, on_delete=models.SET_NULL, null = True)
section = models.OneToOneField(Section, on_delete=models.SET_NULL, null = True)
enrolled_subject = models.ManyToManyField(Subject)
parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, null = True) #parent is from user models
class StudentGrade(models.Model):
PERIOD_CHOICES = [
...
]
student = models.ForeignKey(Student, on_delete=models.CASCADE,)
period = models.CharField(choices=PERIOD_CHOICES, max_length = 30)
subjects = models.ForeignKey(Subject, on_delete=models.CASCADE)
grade = models.DecimalField(default = 75.00, max_digits=4, decimal_places=2)
Views.py
def postgrade(request):
students = Student.objects.all().prefetch_related('enrolled_subject')
context = {
'students': students,
}
if request.method == "POST":
data = request.POST
grade_list = data.getlist('grade')
subject_list = data.getlist('subject')
student = Student.objects.get(pk= data.get('studentid')) #this is where they point my error
i=0
while i < len(grade_list):
enrolled_subject = Subject.objects.get(pk= subject_list[i])
new_grade = StudentGrade(student = student, period= data.get('period'), subjects = enrolled_subject, grade=grade_list[i])
new_grade.save()
i+= 1
Postgrade.html(template)
My queries are displaying properly, the problem is I get an error when i try to save the form
{% for students in students %}
<p>
<a class="btn btn-primary" data-bs-toggle="collapse" href="#collapse{{forloop.counter}}" role="button" aria-expanded="false" aria-controls="collapse{{forloop.counter}}">
{{students.first_name}} {{students.last_name}}
</a>
</p>
<div class="collapse" id="collapse{{forloop.counter}}">
<div class="card card-body">
<form method="POST" >
{% csrf_token %}
<input type="hidden" name="studentid" value="{{students.student.id}}">
<label for="period">Period:</label>
<select name="period" required>
<option selected>First Grading</option>
<option>Second Grading</option>
<option>Third Grading</option>
<option>Fourth Grading</option>
</select><br>
{% for subject in students.enrolled_subject.all %}
<input type="hidden" name="subject" value="{{subject.id}}">
<label for="{{subject.subject_name}}">{{subject.subject_name}}</label>
<input type="text" name="grade">
<br>
{% endfor %}
<button type="submit">upload grade</button>
</form>
</div>
</div>
{% endfor %}
My error says:
ValueError at /Information/postgrade/
invalid literal for int() with base 10: ''
and it points to my views.py:
student = Student.objects.get(pk= data.get('studentid'))
So i feel like there might be something wrong with my template or views, or maybe both
or I should drop out LOL
Thanks for the help
My views.py file is
def studentFeedBack(request):
studentid = ''
courseid = ''
teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = studentid.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = courseid.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = teacherid.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBack.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':studentid.objects.all(),
'courseids':courseid.objects.all(),
'teacherids':teacherid.objects.all(),
}
)
and my models.py file is
class StudentFeedBack(models.Model):
feedbackid = models.AutoField(primary_key=True)
courseid = models.ForeignKey('Course', on_delete=models.CASCADE)
description = models.CharField(max_length=500)
submitdate = models.DateTimeField(auto_now_add=True)
teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE)
studentid = models.ForeignKey('Student', on_delete=models.CASCADE)
option = [('Good','Good'),('Average','Average'),('Bad','Bad')]
rating = models.CharField(max_length=100, choices=option, default='none')
class Course(models.Model):
courseid = models.IntegerField(primary_key=True)
coursedescription = models.CharField(max_length=500)
coursename = models.CharField(max_length=50)
userid = models.IntegerField()
code = models.CharField(max_length=50)
videolink = models.FileField(default='default_link')
createddate = models.DateTimeField()
imagelink = models.URLField(default='default_link')
duration = models.DateTimeField()
longdes = models.TextField()
coursetype = models.CharField(max_length=50)
assignto = models.CharField(max_length=200)
status = models.BinaryField()
def _str_(self):
return self.coursename
class Meta:
db_table = "courseids"
class schoolTeacher(models.Model):
teacherid = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
address = models.CharField(max_length=200)
email = models.EmailField()
contact = models.IntegerField()
passowrd = models.CharField(max_length=13)
image = models.ImageField(default='default.jpg')
regno = models.CharField(max_length=20)
joiningdate = models.DateTimeField()
def _str_(self):
return self.name
class Meta:
db_table = "teacherids"
class Student(models.Model):
studentid = models.IntegerField(primary_key=True)
regno = models.CharField(max_length=20)
name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
contactno = models.CharField(max_length=13)
registrationdate = models.DateTimeField()
address = models.CharField(max_length=200)
password = models.CharField(max_length=13)
imagepath = models.ImageField(max_length=100, default='default.jpg')
sectionid = models.IntegerField()
def _str_(self):
return self.name
class Meta:
db_table = "studentids"
and studentFeedBack html file has the following form
<form action="/studentFeedBack/" method="POST">
{% csrf_token %}
<label for="studentid">Student Id</label>
<!-- <input type="number" name="studentid"><br><br> -->
<select name="studentid" required>
{% for studentid in studentids %}
<option value="{{studentid.id}}">{{studentid.name}}</option>
{% endfor %}
</select><br><br>
<!-- <label for="courseid">Course Id</label>
<input type="number" name="courseid"><br><br> -->
<label for="courseid">Course Id</label>
<select name="courseid" required>
{% for courseid in courseids %}
<option value="{{courseid.id}}">{{courseid.coursename}}</option>
{% endfor %}
</select><br><br>
<label for="teacherid">Teacher Id</label>
<!-- <input type="number" name="teacherid"><br><br> -->
<select name="teacherid" required>
{% for teacherid in teacherids %}
<option value="{{teacherid.id}}">{{teacherid.name}}</option>
{% endfor %}
</select><br><br>
<label for="description" >Feedback</label>
<textarea class="form-control" rows="3" name="description"></textarea><br><br>
<label for="rating">Rating</label><br>
<input type="radio" id="Good" name="rating" value="Good">
<label for="Good">Good</label><br>
<input type="radio" id="Average" name="rating" value="Average">
<label for="Average">Average</label><br>
<input type="radio" id="Bad" name="rating" value="Bad">
<label for="Bad">Bad</label><br><br>
<button type="submit" class="btn btn-primary" >Submit</button>
</form>
The studentFeedBack model has foreign keys from student, schoolTeacher and Course. This is giving error on browser that 'str' object has no attribute 'objects'
Other than that my form is not giving any values in select options and that is also probably because of this error.
The design of the view is the issue
According to the line
studentid =''
studentid remains a string . You could try proper importation of the models.
Try:
views.py
from .models import Course, Student,schoolTeacher,studentFeedBack
def studentFeedBack(request):
#studentid = ''
#courseid = ''
#teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = Student.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = Course.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = schoolTeacher.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBack.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
}
)
Alternatively, Django is superb at handing forms for models
https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#modelform
This will be better for your view as there is no validation at the moment
You could also have:
views.py
...
from django.forms.models import modelform_factory
from .models import studentFeedBack
def studentFeedBack(request):
fields=[
'courseid','description','studentid','teacherid','rating']
form=modelform_factory(studentFeedBack, fields=fields)
if request.method == 'POST':
form=modelform_factory(studentFeedBack, fields=fields, data=request.POST)
## Validates the data submitted
if form.is_valid():
## Creates a studentFeedBack instance
form.save()
## If form is invalid, it will fall through to the template with the incorrect data.
else:
### Handle the incorrect form
pass
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
'form':form,
}
)
forms/studentFeedBack.html
<form action="/studentFeedBack/" method="POST">
{% csrf_token %}
{{form.as_p}}
</form>
https://docs.djangoproject.com/en/3.1/topics/forms/#working-with-form-templates
You may need to add a verbose_name attribute to your model fields:
models.py
class StudentFeedBack(models.Model):
...
teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE, verbose_name="Teacher")
...
https://docs.djangoproject.com/en/3.1/ref/models/fields/#verbose-name
Customize as needed.
I hope this helps you understand Django better.
Edit
The function-based view has the same name as an imported model
For the first view:
from .models import Course, Student,schoolTeacher
from .models import studentFeedBack as studentFeedBackModel
def studentFeedBack(request):
#studentid = ''
#courseid = ''
#teacherid = ''
if request.method == 'POST':
studentid_id = request.POST.get("studentid")
studentid = Student.objects.get(id=studentid_id)
courseid_id = request.POST.get("courseid")
courseid = Course.objects.get(id=courseid_id)
teacherid_id = request.POST.get("teacherid")
teacherid = schoolTeacher.objects.get(id=teacherid_id)
description = request.POST.get("description")
rating = request.POST.get("rating")
studentFeedBackModel.objects.create(
courseid=courseid,
description=description,
studentid=studentid,
teacherid=teacherid,
rating=rating
)
return render(
request,
'forms/studentFeedBack.html',
{
'studentids':Student.objects.all(),
'courseids':Course.objects.all(),
'teacherids':schoolTeacher.objects.all(),
}
)
I am creating a multiple choice quiz and I am not able to save the selected option on the radio button in the database as a new answer. Also, I want you to show if the option matches the correct answer.
When I select one of the options, it appears in the address bar the value of the radio button next to the text, but I want this value to be saved in db.
views.py
def detalhes(request, idProva):
prova = get_object_or_404(Prova,pk=idProva)
model = Prova
template_name = 'polls/detalhes.html' # Default: <app_label>/<model_name>_list.html
context_object_name = 'prova' # Default: object_list
paginate_by = 10
queryset = Prova.objects.all()
usuario = request.user.id
questao = request.POST.get('idQuestao')
try:
questao_selec = prova.questao_set.get(pk=request.POST['questao'])
pagina = paginator.page(page)
resposta = Resposta(resposta=resposta,idQuestao=idQuestao,idResposta=1,respostacerta=1)
resposta.save()
return redirect('/')
except (KeyError,Questao.DoesNotExist):
return render (request,'polls/detalhes.html',{
'prova': prova,
})
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
else:
#questao_selec.votes += 1
questao_selec = Questao(textoQuestao=request.POST.get('textoQuestao'),imagemQuestao=request.FILES('imagemQuestao'),imagem2Questao=request.FILES('imagem2Questao'),perguntaQuestao=request.POST.get('perguntaQuestao'))
resposta_selec = Resposta(idResposta = request.POST.get('idResposta'),idQuestao = request.POST.get('idQuestao'),usuario = request.POST.get('usuario'),resposta = request.POST.get('#mysubmit'))
questao_selec.save()
resposta_selec.save()
return HttpResponseRedirect(reverse('polls:resultados',args=(prova.idProva,)))
detalhes.html
<form id="NPSform" method="GET">
{% if not resposta.usuario %}
<input type="radio" name="scores" id="A" value="A"> A) {{questao.aOpcao}}<br>
<input type="radio" name="scores" id="B" value="B"> B) {{questao.bOpcao}}<br>
<input type="radio" name="scores" id="C" value="C"> C) {{questao.cOpcao}}<br>
<input type="radio" name="scores" id="D" value="D"> D) {{questao.dOpcao}}<br>
<input type="radio" name="scores" id="E" value="E"> E) {{questao.eOpcao}}<br>
<input type="submit" style="display: none;" name="mysubmit" value='{{resposta.resposta}}'>
<button id="btnresposta" class="btn btn-primary" >Selecionar resposta</button>
{% else %}
{{ resposta.resposta }}
{% endif %}
</form>
models.py
class Questao(models.Model):
idQuestao = models.CharField(max_length=7,primary_key=True,null=False)
idProva = models.ForeignKey(Prova,on_delete=models.CASCADE)
idCategoria = models.ManyToManyField(Categoria,default="Categorias")
textoQuestao = models.CharField(max_length=2000,blank=True,null=True)
imagemQuestao = models.FileField(upload_to='static/img/uploads',blank=True,null=True)
imagem2Questao = models.FileField(upload_to='static/img/uploads',blank=True,null=True)
perguntaQuestao = models.CharField(max_length=500,blank=True,null=True)
aOpcao = models.CharField(max_length=500,null=False,blank=True)
bOpcao = models.CharField(max_length=500,null=False,blank=True)
cOpcao = models.CharField(max_length=500,null=False,blank=True)
dOpcao = models.CharField(max_length=500,null=False,blank=True)
eOpcao = models.CharField(max_length=500,null=False,blank=True)
respostaQuestao = models.CharField(max_length=1)
STATUS_QUESTAO_CHOICES = (
(UM,'Ativa'),
(DOIS,'Inativa'),
)
statusQuestao = models.IntegerField('Status de questão',choices=STATUS_QUESTAO_CHOICES,null=False)
QUESTAO_CHOICES = (
(UM,'Múltipla escolha'),
(DOIS,'Discursiva'),
)
tipoQuestao = models.IntegerField('Tipo de questão',choices=QUESTAO_CHOICES,null=False)
def __str__(self):
return self.idQuestao
class Meta:
verbose_name = "Questão"
verbose_name_plural = "Questões"
class Resposta(models.Model):
idResposta = models.CharField(max_length=9,primary_key=True,null=False)
idQuestao = models.ForeignKey(Questao,on_delete=models.CASCADE)
usuario = models.ForeignKey(User,on_delete=models.CASCADE)
resposta = models.CharField(max_length=1)
certaresposta = models.BooleanField(default=True)
def __str__(self):
return self.idResposta
You are accessing request.POST in your view, but you have method=GET in your form.
class Question(models.Model):
"""This class represents a question. It can have 2 or more options."""
created_on = models.DateTimeField(auto_now_add = 1)
title = models.CharField(max_length = 200)
slug = models.SlugField(unique = True, max_length = 200)
class Choice(models.Model):
"""This represents an answer to the Question, and has a foreignkey to it"""
question = models.ForeignKey(Question)
text = models.TextField()
total_votes = models.IntegerField(default = 0)
I want query last question and it's choice Im try but can't get last as form
to get the last item you can do something like:
q = Question.objects.order_by('id').reverse()[0]
and to get the choices:
choices = q.choice_set.all()
To sum-up, this is how your view should look like:
def last_q(request):
return render_to_response('poll/last.html', { 'last_q': Question.objects.order_by('id').reverse()[0] } )
and this is your template:
{% for c in last_q.choice_set.all %}
<input type="radio" name="choice" value="{{ c.id }}" />{{ c.text }}
{% endfor %}
something like that!