Django:在模型窗体上使用Radio选择框 [英] Django: Using Radio select box on model formsets

查看:3220
本文介绍了Django:在模型窗体上使用Radio选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,
我正在使用模型表单来让我的用户编辑他们的相册。我想在每张照片上放置一个收音机选择框,设置为封面图像,以便我可以处理所有照片,并找到应该是专辑封面的照片。问题是,如何使用收音机选择一个字段到表单集,并仍然保持与其余照片相同?这是我当前的代码:

Hey, I'm using a model formset to let my users edit their photo album. I want to put a Radio select box on every photo saying "Set as cover image" so that I can process all the photos and find the one who should be album cover. The problem is how can I a field with radio select on to the formset and still keep it mutal with the rest of the photos? This is my current code:

class ProjectGalleryForm(forms.ModelForm):
    remove_photo = forms.BooleanField()
    # set_as_cover_image = .... ?? <-- what to put?
    class Meta:
        model = Photo
        exclude = (
            'effect',
            'caption',
            'title_slug',
            'crop_from',
            'is_public',
            'slug',
            'tags'
        )


推荐答案

我认为这里的关键是单选按钮实际上不是表单集的一部分:它是父表单的一部分。这是实际的专辑模型,需要知道哪些照片对象是封面图像。所以你想做的就是从单选按钮中显示每个选项以及照片格式中的相应行 - 这很棘手,因为Django无法以这种方式呈现表单域。您将需要手动为每个选项生成HTML。

I think the key here is that the radio button is not actually part of the formset: it's part of the parent form. It's the actual Album model that needs to know which of the Photo objects is the cover image. So what you want to do is to display each option from the radio button alongside its corresponding line in the Photo formset - and that's the tricky bit, because Django can't render form fields in that way. You'll need to produce the HTML for each option manually.

因此,给定这些表单,假设Album模型有一个 cover_image 这是一张OneToOneField照片:

So, given these forms, and assuming the Album model has a cover_image which is a OneToOneField to Photo:

class AlbumForm(forms.modelForm):
    class Meta:
        model = Album

photo_formset = forms.inlineformset_factory(Album, Photo, form=ProjectGalleryForm)

在模板中,您将执行以下操作:

in the template you would do something like:

{% for photo_form in photo_formset %}
    <tr><td>
    {% if photo_form.instance.pk %}
        <input type="radio" id="id_cover_image_{{ forloop.counter }}" name="cover_image" value="{{ photo_form.instance.pk }}">
        <label for="id_cover_image_{{ forloop.counter }}">Use as cover image</label>
    {% endif %>
    </td><td>{{ photo_form.as_p }}</td>
    </tr>
{% endfor %}

这篇关于Django:在模型窗体上使用Radio选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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