上传文件后返回对象ID

时间:2019-05-09 21:14:31

标签: python django django-views

我有一个简单的Django应用程序,用于使用表单上传图像文件。我希望能够在视图函数中使用id(在模型中分配的主键)。如何获得该主键?我觉得我一定缺少简单的东西。

型号:

class image(models.Model):
    image = models.ImageField(upload_to='images/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

views.py:

def image_upload(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            # id = ??????????
            # Some other processing with id...
            return render(request, 'image_uploaded.html', context=context)
    else:
        form = ImageForm()
        return render(request, 'reader/image_form.html', {
        'form': form
})

forms.py

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

1 个答案:

答案 0 :(得分:2)

解决方案是:

dir = 'H:\Projects\test'
files = glob.glob(dir)
files.sort(key=os.path.getmtime)
for i, file in enumerate(files):
    try:    
       os.rename(file, '{dir}/attachment-{i}.txt')
       break
    except:
        print('rename failed')

所保存模型的表单返回实例的方法保存,更多详细信息the-save-method

还请阅读coding-style