Я создаю приложение Python / Flask (как часть моего учебного процесса), которое требует от пользователей выбора параметров при регистрации.
Параметры, сгенерированные мной из db, работают нормально, но параметры, которые я набрал в шаблоне jinja, возвращают: "ValueError: недостаточно значений для распаковки (ожидается 2, получено 1)" когда я заполняю форму с кодом ниже:
form.primary_business_type.choices = request.form.get("PrimaryBusinessType")
и "Недопустимый выбор" для одного SelectField и "Это поле обязательно для заполнения" для SelectMultipleField, когдая заполняю форму с кодом ниже:
form.primary_business_type.choices = \
[(request.form.get("PrimaryBusinessType"), request.form.get("PrimaryBusinessType"))]
Пожалуйста, любая помощь по этому очень приветствуется.
Вот скриншот ошибок: Фактические ошибки в форме
Ниже приведены еще несколько кодов для лучшей наглядности:
forms.py
class CreateAccountWithPhoneForm(FlaskForm):
.......
primary_business_type = SelectField('BUSINESS TYPE:', validators=[DataRequired()])
primary_business_sub_type = SelectField('Sub-Type:', validators=[DataRequired()])
major_brands_or_models = SelectMultipleField('Major Brand/Model:', validators=[DataRequired()])
additional_business_types = SelectMultipleField('Additional Business Types:', validators=[Optional()])
business_categories = SelectMultipleField('BUSINESS CATEGORY:', validators=[DataRequired()])
....
submit = SubmitField('Create Account')
И фактические параметры в шаблоне (примере):
<!-- PrimaryBusinessType -->
{{ form.primary_business_type.label(class="form-control-label mr-2") }}
{% if form.primary_business_type.errors %}
{{ form.primary_business_type(class="form-control form-control_lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.primary_business_type.errors %}
<span> {{ error }}</span>
{% endfor %}
</div>
{% else %}
<select name="PrimaryBusinessType">
<option class="text-secondary">Select...</option>
<option value="AutoDealer">Automobiles</option>
<option value="Clothing">Clothing</option>
<option value="Beverages">Beverages</option>
<option value="Other">Other</option>
</select>
{% endif %}
</div>
<div class="form-group">
<!-- PrimaryBusinessSubType -->
{{ form.primary_business_sub_type.label(class="form-control-label mr-2") }}
{% if form.primary_business_sub_type.errors %}
{{ form.primary_business_sub_type(class="form-control form-control_lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.primary_business_sub_type.errors %}
<span> {{ error }}</span>
{% endfor %}
</div>
{% else %}
<select name="PrimaryBusinessSubType">
<option class="AutoDealer" value="MotorcycleSeller">Motorcycle Seller</option>
<option class="AutoDealer" value="3WheelerSeller">3 Wheeler Seller</option>
<option class="AutoDealer" value="CarSeller">Car Seller</option>
<option class="Clothing" value="Laces">Laces</option>
<option class="Clothing" value="SportsWears">Sports Wears</option>
</select>
{% endif %}
</div>
<div class="form-group">
<!-- MajorBrandOrModel -->
{{ form.major_brands_or_models.label(class="form-control-label mr-2") }}
{% if form.major_brands_or_models.errors %}
{{ form.major_brands_or_models(class="form-control form-control_lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.major_brands_or_models.errors %}
<span> {{ error }}</span>
{% endfor %}
</div>
{% else %}
<select name="MajorBrandOrModel">
<option class="CarSeller" value="Mercedese">Mercedese</option>
<option class="SportsWears" value="Puma">Puma</option>
</select>
{% endif %}
</div>
<div class="form-group">
<!-- AdditionalBusinessTypes-->
{{ form.additional_business_types.label(class="form-control-label mr-2") }}
{% if form.additional_business_types.errors %}
{{ form.additional_business_types(class="form-control form-control_lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.additional_business_types.errors %}
<span> {{ error }}</span>
{% endfor %}
</div>
{% else %}
<select name="AdditionalBusinessTypes" class="selectpicker" multiple data-show-subtext="true" data-live-search="true">
<optgroup label="Auto Dealer">
<option class="AutoDealer" value="MotorcycleSeller">Motorcycle Seller</option>
<option class="AutoDealer" value="3WheelerSeller">3 Wheeler Seller</option>
<option class="AutoDealer" value="CarSeller">Car Seller</option>
</optgroup>
<optgroup label="Cloathing">
<option class="Cloathing" value="Laces">Laces</option>
<option class="Cloathing" value="SportsWears">Sports Wears</option>
<option class="Cloathing" value="TShirts">T Shirts</option>
</optgroup>
</select>
{% endif %}
</div>
<div class="form-group">
<!-- BusinessCategories-->
{{ form.business_categories.label(class="form-control-label mr-2") }} <br>
{% if form.business_categories.errors %}
{{ form.business_categories(class="form-control form-control_lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.business_categories.errors %}
<span> {{ error }}</span>
{% endfor %}
</div>
{% else %}
{% for category in business_categories %}
<div class="form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="BusinessCategories" value="{{ category }}">{{ category }}
</label>
</div>
{% endfor %}
{% endif %}
</div>
Затем точка заполненияполя формы в представлении, где я думаю, что что-то не так:
Использование приведенного ниже кода возвращает ошибку: "Недопустимый выбор" для одного SelectField и "Это полетребуется " для SelectMultipleField
@users.route("/create-account-with-phone", methods=['GET', 'POST'])
def create_account_with_phone():
if current_user.is_authenticated:
return redirect(url_for('main.home'))
form = forms.CreateAccountWithPhoneForm()
form.primary_business_type.choices = \
[(request.form.get("PrimaryBusinessType"), request.form.get("PrimaryBusinessType"))]
form.primary_business_sub_type.choices = \
[(request.form.get("PrimaryBusinessSubType"), request.form.get("PrimaryBusinessSubType"))]
form.major_brands_or_models.choices = \
[(request.form.get("MajorBrandOrModel"), request.form.get("MajorBrandOrModel"))]
form.additional_business_types.choices = \
[(request.form.get("AdditionalBusinessTypes"), request.form.get("AdditionalBusinessTypes"))]
form.business_categories.choices = \
[(request.form.get("BusinessCategories"), request.form.get("BusinessCategories"))]
в то время как,ниже показано: «ValueError: недостаточно значений для распаковки (ожидается 2, получено 1)»
@users.route("/create-account-with-phone", methods=['GET', 'POST'])
def create_account_with_phone():
if current_user.is_authenticated:
return redirect(url_for('main.home'))
form = forms.CreateAccountWithPhoneForm()
form.primary_business_type.choices = request.form.get("PrimaryBusinessType")
form.primary_business_sub_type.choices = request.form.get("PrimaryBusinessSubType")
form.primary_business_sub_type.choices = request.form.get("MajorBrandOrModel")
form.primary_business_sub_type.choices = request.form.get("AdditionalBusinessTypes")
form.primary_business_sub_type.choices = request.form.get("BusinessCategories")
Пожалуйста, еще раз, любая помощь очень ценится. Заранее спасибо