【发布时间】:2015-03-29 08:00:29
【问题描述】:
我有一个带有一些复选框和一些文本的表单,当用户提交数据时,我使用以下表单对象:
class PostForm(forms.Form):
product = forms.MultipleChoiceField(
label='product',
widget=forms.CheckboxSelectMultiple)
text = forms.CharField(label='text', max_length=1000)
def __init__(self, choices, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.fields['product'].choices = choices
但是当我调试代码时,cleaned_data 的帖子完全是空的,data 对象包含所有数据:
<QueryDict: {'text': ['Hello world, this is a test\r\n'], 'product': ['7', '9'], 'csrfmiddlewaretoken': ['QYuwBoW3O5D42oScF2GzYuesTBIZZqRa']}>
更新:
这里是模板:
<h1>Create post</h1>
<textarea rows="10" cols="50" name="text" form="post_form">
Hello world, this is a test
</textarea>
<form action="" method="post" id="post_form">
{% csrf_token %}
<label for="product_id" id="product_id">products: </label>
{% for product in products %}
<input type="checkbox" name="product" value="{{product.id}}">{{product.name}}
{% endfor %}
</select>
<br>
<input type="submit" value="OK">
</form>
这里是视图:
class PostView(AuthenticatedUserView):
template_name = 'trendby/post.html'
def get_if_authenticated(self, request, user):
products = models.Product.objects.filter(user=user)
return render(request, self.template_name, {'products': products})
def post_if_authenticated(self, request, user):
products = models.Product.objects.filter(user=user)
choices = []
for product in products:
choices += [str(product.id)]
form = PostForm(choices, request.POST)
if form.is_valid():
text = form.cleaned_data['text']
post = models.Post(text=text, user=user)
post.save()
return HttpResponse("Post: " + text)
return render(request, self.template_name)
谁能告诉我我能做些什么来修复“cleaned_data”?
谢谢!
【问题讨论】:
-
您的视图是什么样的?
-
我刚刚更新了帖子
标签: python django django-forms