如何从Django选择字段中检索选定的数据?

时间:2019-02-07 03:15:11

标签: django python-3.x django-forms django-templates django-views

如果要根据主题和问题类型在数据库中找到question_description answer_descritptionquestion_image answer_image,请同时使用两个ChoiceField来检索:主题和问题类型。

但是,我不知道该怎么做。我已经看过一些教程并大致了解了我该怎么做,但是我不确定如何在我的案例中执行相同的技术,因为在线上没有很多ChoiceField示例,除了上面有一些通用示例如何使用表单并从数据库中提取数据。

这是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

这是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
    }

这是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)

这是模板:

    {% 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 %}

我会帮助您! 谢谢!

1 个答案:

答案 0 :(得分:1)

表单的cleaned_data属性包含一个字典,该字典将字段名称与边界数据进行映射。从MultiForm文档中,您可以阅读:

  

cleaned_data

     

为每个子表单返回cleaned_data的OrderedDict。

只需提取数据:

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