我有一个模型,并添加了一个Form FileField来获取文件并保存特定对象的所有内容。应该读取,解析文件中的内容并将其存储到模型的synonym_name。
model.py
molecule = models.ForeignKey('MoleculeDictionary', blank=False, null=False)
synonym_type = models.ForeignKey('SynonymType')
synonym_name = models.CharField(max_length=50, blank=True)
def __unicode__(self):
return u'%s' % (self.synonym_name)
这就是我将Form字段添加到模型(admin)页面的方法。
form.py
from django.forms import ModelForm
from django.forms import *
import pdb
import os
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files import File
from idg.models.molecule_synonym import MoleculeSynonym
class MoleculeSynonymForm(ModelForm):
file_upload = FileField(required=False)
print "YES"
def save(self, commit=True):
print 'saving...'
file_upload = self.cleaned_data.get('file_upload', None)
file_upload.seek(0)
with open("../../Downloads/model_file_upload.txt", 'r') as f:
model_file = File(f)
names = model_file.read()
print(names)
form = MoleculeSynonymForm(names)
return super(MoleculeSynonymForm, self).save(commit=commit)
#
class Meta:
model = MoleculeSynonym
我有两个问题:
分子同义词""成功添加。
更新:试过这个: 我知道这可能是彻头彻尾的愚蠢:
try:
synonym_name = MoleculeSynonym.objects.create(synonym_name=names)
except:
synonym_name = None
print synonym_name
synform = MoleculeSynonymForm(instance=synonym_name)
print语句打印无。
答案 0 :(得分:0)
我没有得到你想要的东西,但如果这有助于看看:
class MoleculeSynonymForm(ModelForm):
file_upload = FileField(required=False)
class Meta:
model = MoleculeSynonym
def clean_file_upload(self):
file_upload = self.cleanded_data['file_upload']
if file_upload:
model = YourModel()
model.file = file_upload
model.save()
else:
raise errors
将YourModel替换为您的模型和文件以及模型文件字段。