我正在使用Django处理一个项目,我动态创建了一个输入字段并尝试提交它,但是我却没有这样做,我在网上搜索了一下,发现可以用formset_factory完成,但是当我尝试使用它时,我收到此错误
CatName = int(float(request.POST.get('CatName')))
TypeError: float() argument must be a string or a number, not 'NoneType'
这是我的代码
form.html
<form action="." method="post" id="PostCat__form">{% csrf_token %}
<input type="hidden" name="deyHidden" value="category_hidden">
{% comment %} {{ catForm | crispy }}
<input type="hidden" name="deyHidden" value="category_hidden"> {% endcomment %}
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<div class="form-group">
<h6 id="PostCat__show"></h6>
<img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostCat__img">
<button class="btn btn-outline-info" type="submit" id="PostCat__submit">Create</button>
</div>
</form>
model.py
class Category(models.Model):
CatName = models.CharField(max_length=100)
view.py
myFormCat = CatPostForm(request.POST)
CatName = int(float(request.POST.get('CatName')))
# print(CatName)
formset = formset_factory(FormsetForm, CatName=CatName)(request.POST)
if myFormCat.is_valid() and formset.is_valid():
for form_c in formset:
if not form_c.cleaned_data['CatName']:
Category.objects.get_or_create(CatName=CatName)
response_data = {
'SType': 'success',
'message': "Saved Successfully"
}
return HttpResponse(json.dumps(response_data), content_type="application/json")
forms.py
class CatPostForm(forms.ModelForm):
class Meta:
model=Category
fields = ['CatName']
请问我该怎么做,这样我才能成功提交表单
答案 0 :(得分:0)
在您的views.py
from django.forms import formset_factory
CatPostFormSet = formset_factory(CatPostForm)
catformset = CatPostFormSet() #this goes to your page context. do the validations here also after the post
在您的form.html
<form method="post">
{{ formset.management_form }}
{{formset}}
</form>