簡體   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