无法在django的multiChoiceField中获取帖子数据 [英] Unable to get post data in a multipleChoiceField with django

查看:936
本文介绍了无法在django的multiChoiceField中获取帖子数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些复选框和一些文本的表单,当用户提交数据时,我使用以下表单对象:

I have a form with some checkBoxes and some text, when the user submit the data I use the following form object:

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

但是当我调试代码,帖子 clean_data 完全为空,而数据对象包含所有数据:

But when I debug the code, the post cleaned_data is totally empty, and the data object contains all the 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)

C有人告诉我可以做些什么来修复'cleaning_data'?

Can anybody tell me what can I do to fix the `cleaned_data'?

谢谢!

推荐答案

class PostForm(ModelForm):
    class Meta:
        model = models.Post
        fields = ['text', 'products', 'image']
        widgets = {
            'text': Textarea(attrs={'cols': 80, 'rows': 10}),
            'products': SelectMultiple(),
        }

class PostView(AuthenticatedUserView):
    template_name = 'myapp/post.html'

    def get_if_authenticated(self, request, user):
        form = PostForm()
        return render(request, self.template_name, {"form": form})

    def post_if_authenticated(self, request, user):
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = user
            post.save()
            return HttpResponseRedirect(reverse('myapp:actions'))
        return render(request, self.template_name, {"form": form})

模板:

{% if form.errors %}<p><strong>{{ form.errors }}</strong></p>{% endif %}

<form method="post" enctype="multipart/form-data"  action="">
    {% csrf_token %}
    {% for field in form %}
        {{ field.label_tag }} {{ field }} <br>
    {% endfor %}
    <input type="submit" value="OK">
</form>

这篇关于无法在django的multiChoiceField中获取帖子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆