簡體   English   中英

如何區分Django中以一種形式提交的多個forms?

[英]How to distinguish between multiple forms submitted in one form in Django?

我有多個 forms 的相同基礎 class 像這樣:

class DatabaseForm(forms.Form):
    active = forms.BooleanField(required=False)  # Determines, if username and password is required
    username = forms.CharField(label="Username", required=False)
    password = forms.CharField(label="Password", required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['active'].label = self.label

    def clean(self):
        cleaned_data = super(DatabaseForm, self).clean()
        active = cleaned_data.get("ative")
        username = cleaned_data.get("username")
        password = cleaned_data.get("password")
        if active and not (username and password):
            raise forms.ValidationError("Please fill in the required database configuration")

        return cleaned_data


class MySQLForm(DatabaseForm):
    label = "MySQL"


class PostgreSQLForm(DatabaseForm):
    label = "PostgreSQL"


class SqliteForm(DatabaseForm):
    label = "Sqlite3"

所以只有當用戶選擇一個數據庫時,他必須為它填寫用戶名和密碼。

在我的模板中,表單如下所示:

<form action="." method="post">
    {% csrf_token %}
    {{ mysql_form }}
    {{ postgres_form }}
    {{ sqlite_form }}
    <a id="database-submit-btn" href="#submit"
    class="btn btn-success submit-button">Submit</a>
</form>

問題:當用戶通過選擇“活動”字段選擇數據庫時,其他數據庫的“活動”字段設置為 True。 似乎我無法區分多個字段,因為它們在 POST 請求中具有相同的鍵(但我不確定這是整個問題): 'username': ['mysql test', 'postgres test', 'sqlite test'], 'password': ['mysql password', 'postgres password', 'sqlite password']

我怎樣才能讓它工作並保持代碼可擴展?

您可以在初始化 forms 時傳遞prefix參數,這為每個字段名稱提供一個前綴,並允許您擁有多個具有相同字段名稱的 forms

def foo(request):
    if request.method == 'POST':
        mysql_form = MySQLForm(request.POST, prefix='mysql')
        postgres_form = PostgreSQLForm(request.POST, prefix='postgres')
        sqlite_form = SqliteForm(request.POST, prefix='sqlite')
    else:
        mysql_form = MySQLForm(prefix='mysql')
        postgres_form = PostgreSQLForm(prefix='postgres')
        sqlite_form = SqliteForm(prefix='sqlite')

或者您可以為 class 本身中的每個表單硬編碼一個前綴

class MySQLForm(DatabaseForm):
    label = "MySQL"
    prefix = "mysql"


class PostgreSQLForm(DatabaseForm):
    label = "PostgreSQL"
    prefix = "postgresql"


class SqliteForm(DatabaseForm):
    label = "Sqlite3"
    prefix = "sqlite3"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM