Я пытаюсь выполнить .is_valid()
после запроса POST с моей формой.
form = DrinkForm(request.POST)
Таким образом, «проблема» в том, что у этой формы есть другие параметры.
forms.py:
class DrinkForm(forms.Form):
def __init__(self, language, account_id, configurations, *args, **kwargs):
super(DrinkForm, self).__init__(*args, **kwargs)
translation.activate(language)
При этом я не знаю, как связать форму (и не могу найти руководство или пример по этому делу).
Когда Я печатаю свою форму, вызванную в поле зрения, с ее обычными параметрами, все в порядке, но если я добавлю request.POST
, я ничего не получу.
form_ok = DrinkForm('english', request.session['account_id'], configurations) # OK
form_not_ok = DrinkForm(request.POST) # Needs parameters
form_how_to = DrinkForm('english', request.session['account_id'], configurations, request.POST) # How to?
РЕДАКТИРОВАТЬ: добавлены коды формы и просмотра
def create_drink(request):
if request.method == 'POST':
c = {}
c.update(csrf(request))
data = DrinkForm.build_create_data(request.POST)
try: # Tries to create the new drink
account = Account.objects.get(id=request.session['account_id'])
drinks_conf = DrinksConf.objects.get(account_id=request.session['account_id'])
form = DrinkForm(get_language(request), request.session['account_id'], drinks_conf, request.POST)
print(form) # Nothing is printed!
if form.is_valid():
print('valid?') # Not printed!
with transaction.atomic():
stock = DrinkStock.objects.create(account=account, stock=0)
Drink.objects.create(account=account, name=data['name'], cost=data['cost'], stock=stock,
stock_by=data['stock_by'])
return JsonResponse(DRINK_CREATE_SUCCESS)
else:
print('oh no not valid') # Neither printed!! What the..?
return JsonResponse(form_error_response(form.errors))
except: # Unknown exception
return JsonResponse(UNKNOWN_EXCEPTION)
forms.py:
class DrinkForm(forms.Form):
def __init__(self, language, account_id, drinks_conf, *args, **kwargs):
super(DrinkForm, self).__init__(*args, **kwargs)
translation.activate(language)
self.account_id = account_id # will be used in the future
self.drinks_conf = drinks_conf
options = (
(1, translation.gettext('Units')),
(3, translation.gettext('Litters'))
)
self.fields['name'] = forms.CharField(
max_length=100,
required=True,
label=translation.gettext('Name'),
widget=forms.TextInput(attrs={'class': 'form-control dynamic_object_submit'})
)
self.fields['cost'] = forms.DecimalField(
max_digits=14,
decimal_places=2,
required=True,
label=translation.gettext('Cost'),
widget=forms.NumberInput(attrs={'class': 'form-control dynamic_object_submit'})
)
self.fields['stock_by'] = forms.ChoiceField(
required=True,
label=translation.gettext('Stock/cost by'),
choices=options,
widget=forms.Select(attrs={'class': 'form-control dynamic_object_submit'})
)
def clean_cost(self):
if self.drinks_conf.cost_control is True:
data = self.cleaned_data['cost']
if data < 0:
raise forms.ValidationError(translation.gettext("Cost can't be negative"))
@staticmethod
def build_create_data(querydict):
return {
'name': querydict.get('name', None),
'cost': querydict.get('cost', None),
'stock_by': querydict.get('stock_by', None),
}