Majed Saaeddin
Majed Saaeddin

Reputation: 81

How to retrieve selected data from Django Choice Field?

I want to retrieve the question_description answer_descritption and question_image answer_image if found in the database according to topic and question type using two ChoiceField for both: Topic and Question Type.

However, I don't know how to do that. I have seen some tutorials and gotten glimpses of what I have to do, but I am not sure how to preform the same techniques on my case because online there are not that many ChoiceField examples, except that there are general examples on how to use forms and extract data from the database.

This is the models.py

from django.db import models
from home.choices import *

# Create your models here.

class Topic(models.Model):
    topic_name = models.IntegerField(
                    choices = question_topic_name_choices, default = 1)
    def __str__(self):
        return '%s' % self.topic_name

class Image (models.Model):
    image_file = models.ImageField()

    def __str__(self):
        return '%s' % self.image_file

class Question(models.Model):
    question_type = models. IntegerField(
                    choices = questions_type_choices, default = 1)
    question_topic = models.ForeignKey(    'Topic',
                                    on_delete=models.CASCADE,
                                    blank=True,
                                    null=True)
    question_description = models.TextField()
    question_answer = models.ForeignKey(    'Answer',
                                    on_delete=models.CASCADE,
                                    blank=True,
                                    null=True)
    question_image = models.ForeignKey(    'Image',
                                    on_delete=models.CASCADE,
                                    blank=True,
                                    null=True)

    def __str__(self):
        return '%s' % self.question_type

class Answer(models.Model):
    answer_description = models.TextField()
    answer_image = models.ForeignKey(    'Image',
                                    on_delete=models.CASCADE,
                                    blank=True,
                                    null=True)
    answer_topic = models.ForeignKey(    'Topic',
                                    on_delete=models.CASCADE,
                                    blank=True,
                                    null=True)
    def __str__(self):
        return '%s' % self.answer_description

This is the forms.py

from django import forms
from betterforms.multiform import MultiModelForm
from .models import Topic, Image, Question, Answer
from .choices import questions_type_choices, question_topic_name_choices

class TopicForm(forms.ModelForm):
    topic_name      =   forms.ChoiceField(
                    choices=question_topic_name_choices,
                    widget = forms.Select(
                    attrs = {'class': 'home-select-one'}
                        ))

    class Meta:
        model = Topic
        fields = ['topic_name',]
        def __str__(self):
            return self.fields


class QuestionForm(forms.ModelForm):
    question_type =   forms.ChoiceField(
                    choices= questions_type_choices,
                    widget = forms.Select(
                    attrs = {'class': 'home-select-two'},
                        ))

    class Meta:
        model = Question
        fields = ['question_type',]
        def __str__(self):
            return self.fields


class QuizMultiForm(MultiModelForm):
    form_classes    =   {
                'topics':TopicForm,
                'questions':QuestionForm
    }

This is the views.py

from django.shortcuts import render, render_to_response
from django.views.generic import TemplateView
from home.models import Topic, Image, Question, Answer
from home.forms import QuizMultiForm




class QuizView(TemplateView):
    template_name = 'index.html'
    def get(self, request):
  # What queries do I need to put here to get the question and answer's description according to the ChoiceField input
        form = QuizMultiForm()
        return render (request, self.template_name, {'form': form})

    def post(self, request):
        form = QuizMultiForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['topic_name', 'question_type'] # I don't know what to put here!

        args = {'form': form, 'text': text}
        return render (request, self.template_name, args)

This is the template:

    {% extends 'base.html' %}
      {% block content %}
            <form  method="POST">
              {% csrf_token %}
              {{ form.as_p }}
              <button type="submit" id="home-Physics-time-button">It is Physics Time</button>
              <h1> {{ text }} </h1>
            </form>
        {% endblock content %}

I would appropriate the help! Thank you!

Upvotes: 0

Views: 2230

Answers (1)

Raydel Miranda
Raydel Miranda

Reputation: 14360

The cleaned_data attribute of the form, contains a dictionary that maps the name of the field with the bounded data. And from the MultiForm docs you can read:

cleaned_data

Returns an OrderedDict of the cleaned_data for each of the child forms.

Just extract data like this:

topic_name = form.cleaned_data['topics']['topic_name']
question_type = form.cleaned_data['question']['question_type']
# And so on ...

Upvotes: 1

Related Questions