我有两个模型,Room
和Image
。 Image
是一个通用模型,可以附加到任何其他模型上。我想在用户发布有关房间的信息时为用户提供一个表单来上传图像。我已经编写了有效的代码,但恐怕我已经以一种艰难的方式完成了它,特别是以违反 DRY 的方式。
希望对django表单更熟悉的人能指出我哪里出错了。
更新:
我试图澄清为什么我在对当前答案的评论中选择了这个设计。总结一下:
我并没有简单地ImageField
在Room
模型上放置一个,因为我想要多个与 Room 模型相关联的图像。我选择了一个通用的 Image 模型,因为我想将图像添加到几个不同的模型中。我考虑的替代方案是单个Image
类上的多个外键,这看起来很混乱,或者多个Image
类,我认为这会使我的架构混乱。我在第一篇文章中没有说清楚,对此我深表歉意。
看到到目前为止没有一个答案解决了如何使这个更干燥的问题,我确实提出了自己的解决方案,即将上传路径作为类属性添加到图像模型上,并在每次需要时引用它。
# Models
class Image(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
image = models.ImageField(_('Image'),
height_field='',
width_field='',
upload_to='uploads/images',
max_length=200)
class Room(models.Model):
name = models.CharField(max_length=50)
image_set = generic.GenericRelation('Image')
# The form
class AddRoomForm(forms.ModelForm):
image_1 = forms.ImageField()
class Meta:
model = Room
# The view
def handle_uploaded_file(f):
# DRY violation, I've already specified the upload path in the image model
upload_suffix = join('uploads/images', f.name)
upload_path = join(settings.MEDIA_ROOT, upload_suffix)
destination = open(upload_path, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
return upload_suffix
def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'):
apartment = Apartment.objects.get(id=apartment_id)
if request.method == 'POST':
form = form_class(request.POST, request.FILES)
if form.is_valid():
room = form.save()
image_1 = form.cleaned_data['image_1']
# Instead of writing a special function to handle the image,
# shouldn't I just be able to pass it straight into Image.objects.create
# ...but it doesn't seem to work for some reason, wrong syntax perhaps?
upload_path = handle_uploaded_file(image_1)
image = Image.objects.create(content_object=room, image=upload_path)
return HttpResponseRedirect(room.get_absolute_url())
else:
form = form_class()
context = {'form': form, }
return direct_to_template(request, template, extra_context=context)