我有兩個模型,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