我正在建立一个用户自己登录的网站,然后上传一个文件,该文件将被存储以供用户稍后使用。
我的model.py是:
class Ontology(models.Model):
name = models.TextField(max_length=50)
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
file = models.FileField(default="", validators=[validate_file_extension])
my forms.py
from django import forms
from .models import Ontology
class UploadOntologyForm(forms.ModelForm):
class Meta:
model = Ontology
fields = ('file',)
在views.py中的我有:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadOntologyForm
from django.views.generic import CreateView
from .handle_upload_owl import *
def index(request):
if request.method == 'POST':
form = UploadOntologyForm(request.POST, request.FILES)
if form.is_valid():
if not handle_uploaded_file(request.FILES['file']):
form.save()
return HttpResponseRedirect('/ontology/')
else:
form = UploadOntologyForm()
return render(request, 'index.html', {'form':form})
和后者handle_upload_owl.py
def handle_uploaded_file(thisFile):
if thisFile._size > 5242880:
return False
else:
with open('media/' + str(thisFile), 'wb+') as destination:
for chunk in thisFile.chunks():
destination.write(chunk)
return True
编辑:添加了CustomUser Class
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
institution = models.TextField(max_length=254)
我的应用正在正确加载和存储文件,但没有添加数据库中的条目,甚至与上传它的登录用户无关。
我是django的新手,我对此并不满意。怎么了?
答案 0 :(得分:1)
首先,我不明白你为什么不放弃'在
if not handle_uploaded_file(request.FILES['file'])
此外,您应该在表单中定义一个干净的方法,以便进行检查,而不是制作另一个文件:
class UploadOntologyForm(forms.ModelForm):
class Meta:
model = Ontology
fields = ('file',)
def clean_file(self):
file= self.cleaned_data['file']
try:
#validate content type
main, sub = file.content_type.split('/')
if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'png']):
raise forms.ValidationError(u'Please use a JPEG or PNG image.')
#validate file size
if len(file) > (10000 * 1024):
raise forms.ValidationError(u'File size may not exceed 10M.')
except AttributeError:
"""
Handles case when we are updating the user profile
and do not supply a new avatar
"""
pass
return file
最后,您的索引视图变为:
def index(request):
if request.method == 'POST':
form = UploadOntologyForm(request.POST, request.FILES)
if form.is_valid():
ontology= form.save(commit=False)
# commit=False tells Django that "Don't send this to database yet, I have more things I want to do with it."
ontology.name = "Whatever name"
ontology.user = request.user # Set the user object here
ontology.save() # Now you can send it to DB
return HttpResponseRedirect('/ontology/')
else:
form = UploadOntologyForm()
return render(request, 'index.html', {'form':form})
答案 1 :(得分:0)
这是我的尝试:
forms.py
:
class UploadOntologyForm(forms.ModelForm):
class Meta:
model = Ontology
fields = ('file',)
def __init__(self, *args, **kwargs):
# Here we get our 'req' object. passed from the
# construction of this form in views.py
self.request = kwargs.pop("req")
# that's all. then we continue the init logic with super.
super(UploadOntologyForm, self).__init__( *args, **kwargs)
def save(self):
# At this point data is processed and 'cleaned'
data = self.cleaned_data
# We construct our Ontology with the file and user
o = Ontology(
user = self.request.user,
file = data['file'])
# And finally save it!
o.save()
您更新的views.py
(对UploadOntologyForm
的调用已更改):
def index(请求)
if request.method == 'POST':
form = UploadOntologyForm(request.POST, request.FILES, req=request)
if form.is_valid():
if not handle_uploaded_file(request.FILES['file']):
form.save()
return HttpResponseRedirect('/ontology/')
else:
form = UploadOntologyForm(req=request)
return render(request, 'index.html', {'form':form})