2016-07-07 76 views
0

我正在使用表格通過dropzone.js上傳圖片。圖片被保存並上傳正常。但是它創建了一個帶有空字段的新模型。我想將圖片保存到我參考的現有模型中。但我似乎無法找到引用它的解決方案。這裏是我的代碼:保存已上傳的圖像到exisitng Django中的模型

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> 

任何幫助將非常感激!謝謝!

回答

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請求,這會將當前與模型相關聯的圖像(如果有)附加到表單字段,然後纔會將其發送到瀏覽器。

+0

也適用,謝謝! :) – Progph

+0

@Progph [感謝評論部分](http://meta.stackexchange.com/a/126184) –

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}) 
相關問題