当我上传的图片,我看到它在我的项目上载了两次。 这两个位置是/Users/myproject/media/
和/Users/myproject/media/assets/uploaded_files/username/
。 我希望待上传图片只有后者。 为什么两个副本上传,以及如何避免呢?
在settings.py:
MEDIA_URL="/media/"
MEDIA_ROOT = '/Users/myproject/media/'
这里是models.py
UPLOAD_FILE_PATTERN="assets/uploaded_files/%s/%s_%s"
def get_upload_file_name(instance, filename):
date_str=datetime.now().strftime("%Y/%m/%d").replace('/','_')
return UPLOAD_FILE_PATTERN % (instance.user.username,date_str,filename)
class Item(models.Model):
user=models.ForeignKey(User)
price=models.DecimalField(max_digits=8,decimal_places=2)
image=models.ImageField(upload_to=get_upload_file_name, blank=True)
description=models.TextField(blank=True)
编辑:我使用formwizards。 这里是views.py:
class MyWizard(SessionWizardView):
template_name = "wizard_form.html"
file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
#if you are uploading files you need to set FileSystemStorage
def done(self, form_list, **kwargs):
for form in form_list:
print form.initial
if not self.request.user.is_authenticated():
raise Http404
id = form_list[0].cleaned_data['id']
try:
item = Item.objects.get(pk=id)
print item
instance = item
except:
item = None
instance = None
if item and item.user != self.request.user:
print "about to raise 404"
raise Http404
if not item:
instance = Item()
for form in form_list:
for field, value in form.cleaned_data.iteritems():
setattr(instance, field, value)
instance.user = self.request.user
instance.save()
return render_to_response('wizard-done.html', {
'form_data': [form.cleaned_data for form in form_list], })
def edit_wizard(request, id):
#get the object
item = get_object_or_404(Item, pk=id)
#make sure the item belongs to the user
if item.user != request.user:
raise HttpResponseForbidden()
else:
#get the initial data to include in the form
initial = {'0': {'id': item.id,
'price': item.price,
#make sure you list every field from your form definition here to include it later in the initial_dict
},
'1': {'image': item.image,
},
'2': {'description': item.description,
},
}
print initial
form = MyWizard.as_view([FirstForm, SecondForm, ThirdForm], initial_dict=initial)
return form(context=RequestContext(request), request=request)