我有以下型号:
class Quiver(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
is_default = models.BooleanField(default=False)
type = models.CharField(max_length=1, choices=QUIVER_TYPES)
category = models.CharField(max_length=255, choices=QUIVER_CATEGORIES)
def __unicode__(self):
return u'[%s] %s %s quiver' % (
self.user.username,
self.get_type_display(),
self.get_category_display())
class Image(models.Model):
photo = models.ImageField(upload_to=get_upload_file_path)
is_cover = models.BooleanField(default=False)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
def save(self, *args, **kwargs):
try:
this = Image.objects.get(pk=self.pk)
if this.photo != self.photo:
this.photo.delete(save=False)
except Image.DoesNotExist:
pass
super(Image, self).save(*args, **kwargs)
class Surfboard(models.Model):
quiver = models.ForeignKey(Quiver)
brand = models.CharField(max_length=255)
model = models.CharField(max_length=255)
length = models.CharField(max_length=255)
width = models.CharField(max_length=255, blank=True)
thickness = models.CharField(max_length=255, blank=True)
volume = models.CharField(max_length=255, blank=True)
images = generic.GenericRelation(Image)
def __unicode__(self):
return u'%s %s %s' % (self.length, self.brand, self.model)
def get_cover_image(self):
"Returns the cover image from the images uploaded or a default one"
for image in self.images.all():
if image.is_cover:
return image
return None
我希望能够在我的前端视图/surfboard/add 中拥有与管理员相同的表单:
作为一个新的 Django 粉丝和用户,我开始从头开始创建表单。无法通过将外键“quiver”包含在下拉列表中来做我想做的事,我在文档中找到了 ModelForm,并决定使用它,所以我得到了:
class SurfboardForm(ModelForm):
class Meta:
model = Surfboard
在我看来,它看起来像这样,它已经是一个好的开始:
所以现在,我想要一种同时添加图片的方法,它们通过通用关系链接到冲浪板。在这里,我找不到像在管理员中那样执行实现的方法,并且感到沮丧。有什么建议吗?
谢谢!