默认选择第一个图像作为modelformset_factory的特征

时间:2017-05-13 07:25:14

标签: django python-2.7 django-forms django-templates django-views

我需要在默认情况下将第一张图片选为特色图片。目前它可以工作,但只有当用户选择特色图像时。

Forms.py

class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image')  
def __init__ (self, *args, **kwargs):
    super(ImageForm, self).__init__(*args, **kwargs)
    self.fields['featured'] = forms.BooleanField( widget = forms.RadioSelect(choices=((self.prefix, 'featured'),)))

    class Meta:
    model = Images
    fields = ['image', 'featured', ]

models.py

from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
# Create your models here.


class Post(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=128)
body = models.CharField(max_length=400)

def __str__(self):
    return self.title

def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)  




class Images(models.Model):
post = models.ForeignKey(Post, default=None)
image = models.ImageField(upload_to=get_image_filename,
                          verbose_name='Image', )
featured = models.BooleanField(default=True)

1 个答案:

答案 0 :(得分:1)

要预先检查单选按钮,请将checked属性传递给RadioSelect。要检查HTML单选按钮,您可以使用:

<input type="radio" checked>

其中checked是输入元素的布尔属性。因此,添加attrs dict来设置属性:

widget = forms.RadioSelect(attrs={'checked': 'true'}, choices=((self.prefix, 'featured'),))