繁体   English   中英

Django表单向导处理

[英]Django form wizard handling

我在理解django表单向导时遇到了一些问题。

主要是,我不了解如何处理form_list。

到目前为止,这是我的看法

class AddLocation(SessionWizardView):
    template_name = "dash/AddLocation.html"

    def processAddLocation(self, form_list, **kwargs):

    def done(self, form_list, **kwargs):
        processAddLocation(form_list)
        return redirect(reverse('location_manager'))

这是我的表格

class regionForm(forms.Form):
    name = forms.CharField(max_length=255)


class locationForm(forms.Form):
    location_name = forms.CharField()
    street_address = forms.CharField()
    city = forms.CharField()
    zip_code = forms.CharField()

(是的,每个表格都是向导的一页)

这是此表单向导最终应保存为的模型

class Location(models.Model):
    region = models.ForeignKey(Region, blank=True, null=True)
    manager = models.ForeignKey(User, blank=True, null=True)
    name = models.CharField(max_length=255)
    street_address = models.TextField(blank=True)  # allowing this blank for the min.
    city = models.CharField(max_length=255, blank=True)
    zip_code = models.CharField(max_length=20, blank=True)
  1. 现在我该如何正确处理form_list?
  2. form_list到底返回什么?
  3. 为什么需要proccessAddLocation方法和完成的方法(这是向我建议的,但我似乎无法理解为什么)。
  4. 如何将2个表格保存到特定模型

朝正确方向的任何指针将不胜感激。

表单列表只是用户已完成的有效表单的列表。 从一种形式创建location与从多种形式创建location相同。 您只需要确保从正确的表单的cleaned_data dict中获取数据即可。

done的视图方法将如下所示:

def done(self, form_list, **kwargs):
    region_form, location_form = form_list
    location = Location(
        street_address=location_form.cleaned_data['street_address']
        # populate other fields here
        ...
    )
    location.save()

    return redirect(reverse('location_manager'))

您需要一个done方法,因为表单向导需要它。 您不需要processAddLocation方法,因此我没有将其包含在答案中。 您可以定义此方法并将位置创建代码移入其中,如果您认为它使代码更易于理解。

对于外键,例如region ,您将必须将cleaned_data['region']转换为region对象。 您可能必须向表单添加验证,以确保您的用户输入有效的区域。 对于这些外键字段, ModelChoiceField可能更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM