我有两个模型,Room
和Image
。 Image
是一个通用的模型,可以钉上任何其他模型。我想在用户发布有关房间的信息时向他们上传图片。我已经编写了可行的代码,但恐怕我已经做到了这一点,特别是以违反DRY的方式。在django的ModelForm中添加一个通用图像字段
希望对django表单更熟悉的人能指出我出错的地方。
更新:
我试图解释,为什么我在评论当前的答案选择了这个设计。总结如下:
我并没有简单地在Room
模型上放置ImageField
,因为我想要多个与Room模型相关的图像。我选择了一个通用的图像模型,因为我想将图像添加到多个不同的模型。我考虑过的替代方案是在一个Image
类中出现多个外键,这看起来很乱,或者是多个Image
类,我认为这些类会混淆我的模式。我在第一篇文章中没有说清楚,所以对此感到抱歉。
看到迄今为止没有答案已经解决了如何使这一点更干DRY我想出了我自己的解决方案,即将上传路径添加为图像模型上的类属性,并引用每次这是必要的。
# 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)
哪里是你的模型代码:
的意见如果request.method == “POST”
? – muhuk 2009-01-22 07:47:44
添加了模型代码 – Prairiedogg 2009-01-22 07:54:43