Django表格不适用于ManyToMany(auth.users)

时间:2016-12-13 13:44:18

标签: django

我正在尝试使用Django创建一个Debt模型。它有一个debtors字段,可以将债务与许多用户联系起来。

它通过Django的管理面板表现我想要的方式,但我不能使用django表单来工作。尽管浏览器显示了可供选择的用户的准确列表,但我可以创建债务,但债务人领域正在清空。

更令人惊讶的是,我认为在模型定义中使用blank=False不应该允许这样做。

models.py

from django.db import models
from django.utils import timezone


class Debt(models.Model):
    author = models.ForeignKey('auth.User', related_name='author')
    name = models.CharField(max_length=200)
    amount = models.FloatField()
    debtors = models.ManyToManyField('auth.User', blank=False)
    invoice = models.FileField(blank=True)
    created_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.name

forms.py

from django import forms

from .models import Debt

class NewDebtForm(forms.ModelForm):

    class Meta:
        model = Debt
        fields = ('name', 'amount', 'invoice', 'created_date', 'debtors')

views.py

from django.shortcuts import render, redirect
from .models import Debt
from .forms import NewDebtForm

def debt_list(request):
    if request.method == "POST":
        form = NewDebtForm(request.POST)
        if form.is_valid():
            debt = form.save(commit=False)
            debt.author = request.user
            debt.save()
    debts = Debt.objects.order_by('created_date')
    form = NewDebtForm()
    return render(request, 'debt_share/debt_list.html',
                  {'debts': debts,
                   'form': form})

debt_list.html

{% extends 'debt_share/base.html' %}

{% block content %}
    {% for debt in debts %}
        <h1>{{ debt.name }}</h1>
        <h2>payé par {{ debt.author }}</h2>
        <h2>{{ debt.amount }} {{ debt.invoice }}</h2>
        <p>
            Concerne
            {% for user in debt.debtors.all %}
                {{ user }}
            {% endfor %}
        </p>
    {% endfor %}

    <form method="POST">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Save</button>
    </form>

{% endblock content %}

1 个答案:

答案 0 :(得分:1)

ModelForms用于多对多关系并使用form.save(commit=False)时,您还必须致电form.save_m2m()。在创建原始对象之后,必须在第二步中保存多对多关系;否则,其ID将不知道。

有关详细信息,请参阅文档中的说明:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#the-save-method