0

我正在将某些媒体上传到特定目录以保护它。使用 inlineformset_factory 对象上传图像。

我遇到的问题是,在管理站点中查看上传的记录时,它似乎将我的 settings.MEDIA_URL (/media/) 附加到上传图像的路径中。

IE。

http://localhost:8000/media/<relative image path>

我希望它改用自定义设置 settings.PROTECTED_MEDIA_URL ('src') 来返回以下路径:

http://localhost:8000/scr/<relative image path>

下面包括我认为是代码的相关部分。

任何见解表示赞赏!

设置.py

...
MEDIA_URL = '/media/'
PROTECTED_MEDIA_URL = '/scr/'
...

模型.py

...
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location = '/home/user/nginx_restricted')

def orig_car_id_folder(instance, filename):
    return 'uploads/images/orig/{0}/{1}'.format(instance.car_id, filename)

class OwnersCar(models.Model):
    brand = models.CharField(max_length=64)
    ...

class OwnersCarImages(models.Model):
    car = models.ForeignKey(OwnersCar)
    orig_image = models.ImageField(
        upload_to=orig_car_id_folder,
        verbose_name='Upload Image',
        storage=fs
    )
    ...
...

管理员.py

from django.contrib import admin
from vehicle_admin_ac.models import OwnersCar, OwnersCarImages

class CarImageInline(admin.TabularInline):
    model = OwnersCarImages
    exclude = ('thumbnail',)

class OwnersCarAdmin(admin.ModelAdmin):
    list_display = ('owner','brand',)
    ordering = ('owner',)
    search_fields = ('owner',)
    inlines = [
        CarImageInline,
    ]

admin.site.register(OwnersCar, OwnersCarAdmin)

网址.py

...
urlpatterns = patterns('',
    url(r'^scr/(?P<protected_image_path>/uploads/images/(thumb|orig)/.*)$',
        'vehicle_admin_ac.views.protected_view',
        name='protected_view'),
    ...
)
...

视图.py

...
@login_required
def protected_view(request, protected_image_path):
    response = HttpResponse()
    url = protected_image_path
    response['Content-Type']=""
    response['X-Accel-Redirect'] = "/protected/{0}".format(url)
    return response

@login_required
def add_vehicle(request):
    ImageFormSet = inlineformset_factory(OwnersCar, OwnersCarImages, form=InitialCarImageForm, extra=3)
    owners_car = OwnersCar()
    if request.method == 'POST':
        form = forms.OwnersCarForm(request.POST, instance=owners_car)
        formset = ImageFormSet(request.POST, request.FILES, instance=owners_car)
        if formset.is_valid() and form.is_valid():
            new_car = form.save(commit=False)
            new_car.owner = request.user
            new_car.save()
            formset.save()  # save() method works fine with 'inlineformset_factory'
            return HttpResponseRedirect(new_car.get_absolute_url())
    else:
        form = forms.OwnersCarForm()
        formset = ImageFormSet()
    return render_to_response('add_new.html',
        {'form': form, 'formset': formset},
        context_instance=RequestContext(request))
...
4

1 回答 1

0

这是我错过的文档相关部分的链接,解释了 base_url 参数。

于 2013-05-27T13:09:38.373 回答