如何在 Django 中使用 "add_fields"?

How can I use "add_fields" in django?

我正在阅读 django 文档并找到 add_fields 方法。

文档说:

"If you need to add additional fields to the formset this can be easily accomplished. The formset base class provides an add_fields method."

我想使用它,但没有示例或说明如何使用 它可以在视图和模板中使用。你能给我一个小的吗 使用此方法的示例?

我举个小例子。 models.py 看起来像这样,

from django.db import models


class Article(models.Model):
    title = models.CharField(max_length=100)
    pub_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

forms.py 看起来像这样,

from django import forms
from django.forms import BaseFormSet
from .models import Article


class ArticleForm(forms.ModelForm):

    class Meta:
        model = Article
        fields = ['title']


class BaseArticleFormSet(BaseFormSet):

    def add_fields(self, form, index):
        super().add_fields(form, index)
        form.fields['body'] = forms.CharField()

views.py 看起来像这样,

from django.shortcuts import render
from django.forms import formset_factory

from .forms import ArticleForm, BaseArticleFormSet

def home(request):
    ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, extra=3)
    context = dict()
    formset = ArticleFormSet()

    if request.method == 'POST':
        formset = ArticleFormSet(request.POST)

        if formset.is_valid():
            print(formset.cleaned_data)

    context['formset'] = formset

    return render(request, 'home.html', context)

最后,home.html会变成这样,

<form method="post">
    {% csrf_token %}
    <table>
        {{ formset }}
    </table>
    <button type="submit">submit</button>
</form>

如您所见,body 字段出现在模板中,但未包含在 Article 模型中。

希望对您有所帮助!