使用Django ModelForm处理一对多关系

时间:2018-10-12 17:08:04

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

我正在尝试扩展Django(2.0版)教程,以便它使用ModelForm创建一个至少具有一个或两个选择的问题。我有两个模型“问题”和“选择”,它们具有一对多的关系。我需要对我的模型,表单,视图和模板执行什么操作才能生成供选择的字段?我看到一些建议Inline的帖子,但这似乎仅适用于管理页面。

投票/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)

投票/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']

投票/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 %}

1 个答案:

答案 0 :(得分:0)

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