将上传的图像保存到Django中的exisitng模型

时间:2016-07-07 09:39:43

标签: python django file web server

我正在使用表单通过dropzone.js上传图片。图片保存并上传得很好。但它正在创建一个带有空字段的新模型。我想将图片保存到我引用的现有模型中。但我似乎无法找到引用它的解决方案。这是我的代码:

views.py (我猜错误就在这里)

def client_view(request, pk):
client = get_object_or_404(Client, pk=pk)

if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        picture = form.save()

    else:
        form = UploadFileForm()

    data = {'form': form}
    return render_to_response('client_view.html', locals(),     RequestContext(request), {"img": picture})

return render(request, 'client_view.html', {'client': client})

urls.py

    url(r'^client/(?P<pk>\d+)/$', client_view, name='client_view'),

forms.py

class UploadFileForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = ('image',)

models.py

class Client(models.Model):
customer_nr = models.IntegerField(null=True)
last_name = models.CharField(max_length=30, null=True)
first_name = models.CharField(max_length=30, null=True)
birthdate = models.DateField(null=True)
address = models.CharField(max_length=50, null=True)
image = models.ImageField("Image", upload_to='files/%Y/%m', null=True, blank=True)

client_view.html

<form action="{% url 'client_view' pk=client.pk %}" class="dropzone"     id="myDropzone">

    {% csrf_token %}

<div class="fallback">
    <input name="file" type="file" multiple/>
</div>

</form>

<script type="text/javascript">
    Dropzone.options.myDropzone = {
    paramName: "image",
    autoProcessQueue : true,
    parallelUploads: 1,

    init: function() {

        this.on("success", function(file, responseText) {

            console.log(responseText);

        });

    }

    };



</script>

任何帮助都会非常感激!谢谢!

2 个答案:

答案 0 :(得分:0)

在我看来,不要使用

form.save()

因为它正在模型中创建一个新实例。相反,我想建议像 -

def client_view(request, pk):
    client = get_object_or_404(Client, pk=pk)

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            client.image = form.cleaned_data.get('image', None)
            picture = client.save()

        else:
            form = UploadFileForm()

        data = {'form': form}
        return render_to_response('client_view.html', locals(), RequestContext(request), {"img": picture})

    return render(request, 'client_view.html', {'client': client})

答案 1 :(得分:0)

Django specified way是使用现有模型实例化ModelForm

views.py

client = get_object_or_404(Client, pk=pk)

if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES, client)
    if form.is_valid():
        picture = form.save()

else:
    form = UploadFileForm(client)

对于POST请求,这会自动将图像保存到正确的模型。

对于GET请求,这会将当前与模型关联的图像(如果有)附加到表单字段,然后再将其发送到浏览器上。