I have a model and have added a Form FileField to take a file and save all their contents for a particular object. The FileField doesn't need to be in the database hence not added as a model.fileField. The content from the file should be read , parsed and added to the synonym_type.
**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)
And this is how I add Form field to the models(admin)page.
**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
I have two questions:
1. How should I save the names to the Synonym_name for a chosen synonym_type and molecule. I use sqlite. My current code doesn't throw any errors other than:
> The molecule synonym "" was added successfully.
2. How do I get the "full path for the file" without hardcoding them in the open statement.