【问题标题】:Using Django ModelForm for one-to-many relationships使用 Django ModelForm 建立一对多关系
【发布时间】:2018-10-12 17:08:03
【问题描述】:

我正在尝试扩展 Django(2.0 版)教程,以便它使用 ModelForm 创建一个至少有一个或两个选项的问题。我有两个模型 Question 和 Choice 具有一对多的关系。我需要对我的模型、表单、视图和模板做什么来生成可供选择的字段?我看过一些建议Inline 的帖子,但这似乎只适用于管理页面。

polls/models.py

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

polls/forms.py

from django.forms import ModelForm
from .models import Choice, Question


class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ['question_text', 'pub_date', 'choice']

polls/views.py

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from .forms import QuestionForm
from .models import Choice, Question



def create_question(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            question_text = form.cleaned_data['question_text']
            pub_date = form.cleaned_data['pub_date']
            question = Question(question_text=question_text, pub_date=pub_date)
            question.save()
            return HttpResponseRedirect(reverse('polls:index'))
    else:
        form = QuestionForm()
    return render(request, 'polls/create-question.html', {'form': form})

polls/create-question.html

{% extends 'polls/base.html' %}
{% block scripts %}{% endblock scripts %}
{% block content %}
    <div class="container">
    <h1>Create question</h1>
    <form action="{% url 'polls:create-question' %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input class="btn btn-lg btn-primary btn-block" type="submit" value="Create">
    </form>
    </div>
{% endblock content %}

【问题讨论】:

    标签: django python-3.x django-views one-to-many modelform


    【解决方案1】:

    要使用 ModelForm,您应该将 ManyToManyField 添加到 Question 模型中,以便将选择与特定问题联系起来。比如choices = models.ManyToManyField(Choice, on_delete=models.CASCADE)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2015-11-10
      相关资源
      最近更新 更多