将多个表单合并为一个视图:如何处理字段错误?

时间:2022-05-26 15:52:53

I have a model like this:

我有这样的模型:

class PersonneTravel(models.Model):
    personne = models.ForeignKey(Personne, verbose_name=_(u'Person'))
    travel = models.TextField(null=True, blank=True, verbose_name=_(u'Travel'))
    date_start = models.DateTimeField(default=None, null=True, blank=True,
                                      editable=True, verbose_name=_(u"Start"))
    date_end = models.DateTimeField(default=None, null=True, blank=True,
                                    editable=True, verbose_name=_(u"End"))
    comments = models.TextField(null=True, blank=True,
                                verbose_name=_(u'Comments'))

I display a list of all the travels of one person. What I wanted to do is to give the possibility to online-edit any of the travels, or to add one, into one view.

我显示一个人的所有旅行列表。我想要做的是提供在线编辑任何旅行或将一个旅行添加到一个视图中的可能性。

Here's how I did:

这是我的方式:

  • create a Form: class PersonneTravelForm with all fields
  • 创建一个Form:PersonneTravelForm类,包含所有字段

  • create a view class IndexView(LoginRequiredMixin, generic.FormView):
  • 创建一个视图类IndexView(LoginRequiredMixin,generic.FormView):

  • overload get_context_data where I create all those forms like this:

    重载get_context_data我在这里创建所有这些形式:

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['travels'] = []
        for ptf in PersonneTravel.objects.filter(
            personne__user=self.request.user,
        ):
            context['travels'].append({
                'obj': ptf,
                'form': PersonneTravelForm({
                    'pk': ptf.pk,
                    'travel': ptf.travel.value,
                    'date_start': ptf.date_start,
                    'date_end': ptf.date_end,
                    'comments': ptf.comments,
                })
            })
    
  • from there in the template, I make a loop:

    从那里的模板,我做了一个循环:

    {% for v in travels %}
        {% with v.form as form %}
            {% include "my_home/travels/travel_form.html" %}
        {% endwith %}{# form #}
    {% endfor %}
    
  • and in the file travel_form.html I display the form

    并在文件travel_form.html中显示表单

  • I've added a bit of javascript with a button "edit" for each form and we the user clicks on it, I slideDown() the form
  • 我为每个表单添加了一些带有“编辑”按钮的javascript,我们用户点击它,我将slideDown()表单

  • When the users clicks "update" to update one travel, the corresponding form is sent as a POST. In the form code, I've created all filters in the form def clean_XXXX(self): with all fields properly "cleaned"
  • 当用户单击“更新”以更新一次旅行时,相应的表单将作为POST发送。在表单代码中,我已经以def clean_XXXX(self)的形式创建了所有过滤器:所有字段都已正确“清理”

  • In the view, I analyze the fields in def form_valid(self, form):
    • if there's a pk in the fields it's for update or delete
      • if all other fields are None I delete
      • 如果所有其他字段都是None我删除

      • if any field is not None then I update
      • 如果任何字段不是None,那么我更新

    • 如果在字段中有一个pk它是用于更新或删除如果所有其他字段都是None我删除如果任何字段不是None然后我更新

    • if there's no pk it's for add a new record, I add one
    • 如果没有pk用于添加新记录,我添加一个

  • 在视图中,我分析def form_valid(self,form)中的字段:如果字段中有pk用于更新或删除,如果所有其他字段都是None我删除如果任何字段不是None然后我更新如果没有pk这是为了添加新记录,我添加一个

My big and only problem here is when there's an error: if I try to add an error while checking the form, and there's a problem I do this, for example:

这里我唯一的问题是当出现错误时:如果我在检查表单时尝试添加错误,并且出现问题,我会这样做,例如:

def form_valid(self, form):
    fc = form.cleaned_data
    d_start = fc['date_start']
    d_end = fc['date_end']
    comments = fc.get('comments', None)

    if d_end and d_start:
        if d_end > datetime.datetime.now().date() > d_start:
            form.add_error('date_start', _(u"Can't start in the past..."))
            form.add_error('date_end', _(u"...and end in the future!"))
            return super(IndexView, self).form_invalid(form)

Everything seems fine... except that the error field goes always into the "add new" blank form, never to the good "edit" form. How would you handle this?

一切似乎都很好......除了错误字段总是进入“添加新的”空白表单,从不到好的“编辑”表单。你会怎么处理这个?

1 个解决方案

#1


0  

You need Django Formsets for this purpose, when you are handling list of forms of a same type. Formset gives you built in features to create new records as well as delete and update older ones.

当您处理相同类型的表单列表时,您需要Django Formsets用于此目的。 Formset为您提供内置功能,以创建新记录以及删除和更新旧记录。

#1


0  

You need Django Formsets for this purpose, when you are handling list of forms of a same type. Formset gives you built in features to create new records as well as delete and update older ones.

当您处理相同类型的表单列表时,您需要Django Formsets用于此目的。 Formset为您提供内置功能,以创建新记录以及删除和更新旧记录。