我有一个应用,我想用图像添加一些字段。当我试图添加记录它的工作正常,但当我尝试编辑记录时,编辑表单不会自动填充其中的任何数据。如何在视图文件中编写一个函数来实现此目的?我的模型是
from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
class Server(models.Model):
name = models.CharField(max_length=200)
ip = models.GenericIPAddressField()
order = models.IntegerField()
image = models.FileField(upload_to='pics/',default='download.jpg')
def __unicode__(self):
return self.name
def get_absolute_url(self):
return reverse('server_edit', kwargs={'pk': self.pk})
我在视图文件中的更新功能是: -
from django.shortcuts import render, redirect, get_object_or_404
from django.forms import ModelForm
import django.forms
from django import forms
from servers.models import Server
def server_update(request, pk, template_name='servers/server_form.html'):
server = get_object_or_404(Server, pk=pk)
form = ServerForm(data=request.POST, files=request.FILES, instance=server)
if form.is_valid():
ser = Server()
ser.name = form.cleaned_data["name"]
ser.ip = form.cleaned_data["ip"]
ser.order = form.cleaned_data["order"]
ser.image = form.cleaned_data["image"]
ser.save()
return redirect('server_list')
return render(request, template_name, {'form':form})
下面 form = ServerForm(data = request.POST,files = request.FILES,instance = server) 这条线是我认为造成的问题,对于没有图像的普通表格 form = ServerForm(data = request.POST,instance = server) 这将在编辑文件中填充数据。但在这种图像记录编辑的情况下它不起作用..
我的模板文件是:
<form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
答案 0 :(得分:1)
请更新您的编辑视图,如下所示: - 该行必须像这样更改 - form = ServerForm(request.POST或None,request.FILES或None,instance = server)
def server_update(request, pk, template_name='servers/server_form.html'):
server = get_object_or_404(Server, pk=pk)
form = ServerForm(request.POST or None, request.FILES or None, instance=server)
if form.is_valid():
edit = form.save(commit=False)
edit.save()
return redirect('server_list')
return render(request, template_name, {'form':form})
答案 1 :(得分:0)
您是否尝试过手动将数据作为字典发送?
form = Form({'charfield': model.charfield, 'imagefield': model.image})
这样你可以尝试其他一些选择。大概你需要发送实际的文件数据,所以你最终会发送:model.image.read()而不仅仅是model.image