Форма Django не прошла валидацию из-за виджета Select
У меня есть Django форма, которая отказывается подтверждать валидность из-за этого виджета Select, я попытался отладить и обнаружил, что конкретное поле формы возвращает None вместо 'Buy' или 'Sell'. Я не могу понять, что не так с моим кодом, хотя подозреваю, что это как-то связано с моим HTML.
models.py
class Transaction(models.Model):
buy = 'BUY'
sell = 'SELL'
transaction_choices = [
(buy, 'Buy'),
(sell, 'Sell'),
]
transaction_type = models.CharField(
max_length=4,
choices=transaction_choices,
default=buy,
)
forms.py
class UpdatePortfolio(forms.ModelForm):
transaction_choices = [
('BUY', 'Buy'),
('SELL', 'Sell'),
]
transaction_type = forms.CharField(
max_length=4,
widget=forms.Select(
choices=transaction_choices,
attrs={
'class': 'form-select',
'name': 'transaction_type',
'id': 'floatingTransaction',
})
)
class Meta:
model = Transaction
fields = (
'transaction_date',
'symbol',
'transaction_date',
'share',
'avg_price',
'cost_basis',
)
def clean_transaction_type(self):
type = self.cleaned_data.get('transaction_type')
if type != 'Buy' or 'Sell':
raise forms.ValidationError(f'{type} is an invalid transaction')
return type
updateportfolio.html
<form action="{% url 'mainpage:update' user.id %}" method="POST">
{% csrf_token %}
<div class="row1">
<div class="transaction_type col-6">
<p>Transaction Type</p>
<select class="form-select" required>
{% for type in form.transaction_type %}
<option>{{ type }}</option>
{% endfor %}
</select>
</div>
<div class="symbol col-6">
<label for="floatingSymbol" class="form-label">Ticker</label>
{{ form.symbol }}
<datalist id="tickers">
{% for ticker in tickers %}
<option value="{{ ticker.tickersymbol }}"></option>
{% endfor %}
</datalist>
</div>
</div>
Update
Эта проблема была решена путем изменения поля 'transaction' и удаления ненужного виджета. Мои обновленные коды показаны ниже.
forms.py
class UpdatePortfolio(forms.ModelForm):
transaction_type = [
('BUY', 'Buy'),
('SELL', 'Sell'),
]
transaction = forms.ChoiceField(
choices=transaction_type,
)
Шаблон
<select name="transaction" class="form-select">
{% for value, text in form.transaction.field.choices %}
<option value="{{ value }}" id="id_transaction_{{ forloop.counter0 }}">{{ text }}</option>
{% endfor %}</select>
models.py
class Transaction(models.Model):
buy = 'BUY'
sell = 'SELL'
transaction_type = [
(buy, 'Buy'),
(sell, 'Sell'),
]
transaction = models.CharField(
max_length=200,
choices=transaction_type,
default=buy,
)