【问题标题】:Why is no data showing out from my database using two Choice Fields?为什么使用两个选择字段没有从我的数据库中显示数据?
【发布时间】:2019-02-12 10:51:07
【问题描述】:

我的项目的目的是从数据库中获取数据并仅在模板上显示。但是,它没有显示任何内容。 有两个选择字段确定要从数据库中检索哪些数据。一种用于主题,一种用于问题类型。

这是我正在使用的 model.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'},
                                ))
            question_answer = forms.CharField(
                            max_length=50,
                            widget  = forms.HiddenInput()
                                )
            question_image = forms.CharField(
                            max_length=50,
                            widget  = forms.HiddenInput()
                                )
            question_description = forms.CharField(
                            max_length=50,
                            widget  = forms.HiddenInput()
                                )
            class Meta:
                model = Question
                fields = ['question_type', 'question_description', 'question_answer', 'question_image']
                def __str__(self):
                    return self.fields


        class QuizMultiForm(MultiModelForm):
            form_classes    =   {
                        'topics':TopicForm,
                        'questions':QuestionForm
            }
            def save(self, commit=True):
                objects = super(QuizMultiForm, self).save(commit=False)

                if commit:
                    topic_name = objects['topic_name']
                    topic_name.save()
                    question_type = objects['question_type']
                    question_type.topic_name = topic_name
                    question_type.save()
                return objects

这是views.py

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



        class QuizView(TemplateView):
            template_name = 'index.html'
            def get(self, request):
                form = QuizMultiForm()
                return render (request, self.template_name, {'form': form})

            def post(self, request):
                topic_name = ""
                question_type = ""
                question_description = ""
                question_answer = ""
                if request.method == 'POST':
                    form = QuizMultiForm(request.POST)
                    if form.is_valid():
                        topic_name = form.cleaned_data['topics']['topic_name']
                        question_type = form.cleaned_data['questions']['question_type']
                        question_description = form.cleaned_data['questions']['question_description']
                        question_answer = form.cleaned_data['questions']['question_answer']
                    args = {'form': form, 'topic_name': topic_name, 'question_type': question_type, 'question_description': question_description, 'question_answer': question_answer}
                return render (request, 'results.html', args)

这是 HTML 文件

  {% extends 'base.html' %}
    {% block content %}
            <table>
              <thead>
                <tr>
                  <th>Topic Number : # {{ topic_name }}</th>
                  <th>Question Type: {{ question_type }}</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                    <td>The Question:{{ question_description }}</td>
                    <td>The Answer:{{ question_answer }}</td>
                </tr>
                <tr>
                  <!-- <td>The Question Image: {{ question_image }}</td> -->
                  <!-- <td>The Answer Image:{{ answer_image }}</td> -->
                </tr>
              </tbody>
            </table>
      {% endblock content %}

这是choices.py

        question_topic_name_choices = (
            (1, "Topic #1: Measurements and Uncertainties"),
            (2, "Topic #2: Mechanics"),
            (3, "Topic #3: Thermal Physics"),
            (4, "Topic #4: Waves"),
            (5, "Topic #5: Electricity and Magnetism"),
            (6, "Topic #6: Circular Motion and Gravitation"),
            (7, "Topic #7: Atomic, Nuclear and Particle Physics"),
            (8, "Topic #8: Energy Production"),
            (9, "Topic #9: Wave Phenomena (HL Only)"),
            (10, "Topic #10: Fields (HL Only)"),
            (11, "Topic #11: Electromagnetic Induction (HL Only)"),
            (12, "Topic #12: Quantum and Nuclear Physics (HL Only)"),
            (13, "Option A: Relativity"),
            (14, "Option B: Engineering Physics"),
            (15, "Option C: Imaging"),
            (16, "Option D: Astrophysics")
                )

        questions_type_choices = (
            (1, "Multiple Choice Questions"),
            (2, "Problem Solving Questions"))

【问题讨论】:

  • 您不需要在forms.py中再次添加字段。

标签: python django django-forms django-templates django-views


【解决方案1】:

您无需在 forms.py 中再次添加字段。这是您的任务的一个简单示例。这里是模型

#your choices
question_topic_name_choices = (
            (1, "Topic #1: Measurements and Uncertainties"),
            (2, "Topic #2: Mechanics"),
            (3, "Topic #3: Thermal Physics"),
            (4, "Topic #4: Waves"),
            (5, "Topic #5: Electricity and Magnetism"),
            (6, "Topic #6: Circular Motion and Gravitation"),
            (7, "Topic #7: Atomic, Nuclear and Particle Physics"),
            (8, "Topic #8: Energy Production"),
            (9, "Topic #9: Wave Phenomena (HL Only)"),
            (10, "Topic #10: Fields (HL Only)"),
            (11, "Topic #11: Electromagnetic Induction (HL Only)"),
            (12, "Topic #12: Quantum and Nuclear Physics (HL Only)"),
            (13, "Option A: Relativity"),
            (14, "Option B: Engineering Physics"),
            (15, "Option C: Imaging"),
            (16, "Option D: Astrophysics")
                )

questions_type_choices = (
            (1, "Multiple Choice Questions"),
            (2, "Problem Solving Questions"))

模型.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

您的表格

#forms.py
class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = ('topic_name',)

现在将表单导入views.py,然后将其传递给模板

从 app.forms 导入 TopicForm

#views.py
def loadTopic(request):

    form=TopicForm()
    return render(request,'template.html',{'form':form})

【讨论】:

  • 我的观点呢?我将如何在模板上查看此内容?我可以将它应用到我已经存在的模型上吗?
  • 将此表单包含在 view.py 文件中并将其传递给视图。如果您不知道,请回复。我会帮你的。
  • 老实说,我不知道如何将您编写的代码应用到我的项目中。
  • 让我们写一个完整的django流程并为您做一些解释。不用担心你会明白的。
  • 对不起,我完全忘记了它。我现在就在上面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多