here is what I would like to achieve:
I would like to be able to edit a database entry through a form which contains multiple different types of Fields (BooleandFields, StringFields etc.) and in these are two flask_wtf FileFields that I would like to have pre-populated (with the file name) when I would have already uploaded the files so I do not have to re-upload x copies of the same thing when I just want to change some entry in the other fields.
here is where I stand:
All the other fields (except the FileFields) are properly pre-populated when I enter the form to edit it.
I am able to upload a file with the combination of Flask-Uploads and UploadSet. through a flask_wtf.file FileField.
In my database I am saving the file name and the file url as Strings.
I have read the flask-wtf file upload as well as the WTForms documentation and I feel a bit lost with what I have to do to emulate what the form needs in order to have the FileField populated as if I already
Here are snippets of the code that I am using:
init.py
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_bootstrap import Bootstrap
from flask_uploads import UploadSet, configure_uploads
[...]
app = Flask(__name__)
[...]
csvfiles = UploadSet('csvfiles')
configure_uploads(app, (csvfiles,))
forms.py
The FileFields in question here are : "dive_posiview" and "dive_ctd"
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from wtforms import StringField, IntegerField, DecimalField, SubmitField,BooleanField
from app import csvfiles
from app.models import User
import re
class DiveForm(FlaskForm):
nb = IntegerField('Dive Number', validators=[DataRequired()])
max_depth = IntegerField('Maximum Depth', validators=[DataRequired()])
launch = StringField("Launch Position: XX°XX.XXXX'N / XX°XX.XXXX'E ", validators=[InputRequired(),validate_Lat_Lon])
recovery = StringField("Recovery Position: XX°XX.XXXX'N / XX°XX.XXXX'E ", validators=[InputRequired(),validate_Lat_Lon])
launch_datetime = DateTimeLocalField('Launch Time',format='%Y-%m-%dT%H:%M', validators=[InputRequired()])
recovery_datetime = DateTimeLocalField('Recovery Time',format='%Y-%m-%dT%H:%M', validators=[InputRequired()])
bottom_start_datetime = DateTimeField('Bottom start time',format='%H:%M', validators=[DataRequired()])
bottom_start_depth = IntegerField('Bottom start depth', validators=[DataRequired()])
bottom_end_datetime = DateTimeField('Bottom end time',format='%H:%M', validators=[DataRequired()])
bottom_end_depth = IntegerField('Bottom end depth', validators=[DataRequired()])
dive_time_total = DateTimeField('Dive total time',format='%H:%M', validators=[DataRequired()])
dive_time_bottom = DateTimeField('Bottom total time', format='%H:%M',validators=[DataRequired()])
dive_posiview = FileField('Posiview log', validators=[FileAllowed(csvfiles, 'CSV file only !')])
dive_ctd = FileField('CTD log', validators=[FileAllowed(csvfiles, 'CSV file only ! ')])
[...]
submit = SubmitField('Validate')
routes.py
#app.route('/cruises/<cruisename>/<diveId>/edit',methods=['GET','POST'])
def dive_edit(cruisename,diveId):
try:
c = Cruises.query.filter_by(name=cruisename).first_or_404()
d = Dives.query.filter_by(cruise_id=c.id,id=diveId).first_or_404()
if request.method == "POST":
form = DiveForm(formdata = request.form)
if form.validate_on_submit():
dive = d
dive.nb = form.nb.data
dive.max_depth = form.max_depth.data
dive.launch = form.launch.data
dive.recovery = form.recovery.data
dive.launch_datetime = form.launch_datetime.data
dive.recovery_datetime = form.recovery_datetime.data
dive.bottom_start_datetime = form.bottom_start_datetime.data
dive.bottom_start_depth = form.bottom_start_depth.data
dive.bottom_end_datetime = form.bottom_end_datetime.data
dive.bottom_end_depth = form.bottom_end_depth.data
dive.dive_time_total = form.dive_time_total.data
dive.dive_time_bottom = form.dive_time_bottom.data
dive_folder = cruisename+'/Dive'+str(form.nb.data)
filename_posiview = csvfiles.save(request.files['dive_posiview'],folder=dive_folder)
url_posiview = csvfiles.url(filename_posiview)
filename_ctd = csvfiles.save(request.files['dive_ctd'],folder=dive_folder)
url_ctd = csvfiles.url(filename_ctd)
dive.posiview_filename = filename_posiview
dive.posiview_url = url_posiview
dive.ctd_filename = filename_ctd
dive.ctd_url = url_ctd
dive.sampling_nets = form.sampling_nets.data
dive.sampling_shovel = form.sampling_shovel.data
dive.sampling_drill = form.sampling_drill.data
dive.sampling_niskin = form.sampling_niskin.data
dive.sampling_push_cores = form.sampling_push_cores.data
dive.sampling_he_sampler = form.sampling_he_sampler.data
dive.sampling_arm_action = form.sampling_arm_action.data
dive.sampling_GBS = form.sampling_GBS.data
dive.sampling_GBC = form.sampling_GBC.data
dive.sampling_IMGAM = form.sampling_IMGAM.data
dive.sensor_CTD = form.sensor_CTD.data
dive.sensor_CODA = form.sensor_CODA.data
dive.sensor_sonar = form.sensor_sonar.data
dive.sensor_MiniPos = form.sensor_MiniPos.data
dive.sensor_MiniPos_calibrated = form.sensor_MiniPos_calibrated.data
dive.action_device_deployed = form.action_device_deployed.data
dive.action_device_recovered = form.action_device_recovered.data
dive.action_mosaicing = form.action_mosaicing.data
dive.action_3D_imaging = form.action_3D_imaging.data
db.session.commit()
# execute jupyter convert script for that dive
if filename_ctd is not None and filename_posiview is not None:
summary_file_path = os.path.abspath(os.curdir)+'/app/static/jupyter/scientific_summary_dive'+str(form.nb.data)+'.html'
if not path.exists(summary_file_path) :
paths = "POSIVIEW_PATH="+csvfiles_path+'/'+filename_posiview
paths += " CTD_PATH="+csvfiles_path+'/'+filename_ctd
thread = threading.Thread(target=os.system, args=( (paths+" jupyter nbconvert --to html --execute app/static/jupyter/dive_scientific_summary.ipynb --output scientific_summary_dive"+str(form.nb.data)),))
thread.daemon = True
thread.start()
return redirect(url_for('cruise',cruisename=cruisename))
else :
form = DiveForm(obj = d)
# NOT WORKING
if os.path.isfile(csvfiles_path+'/'+d.ctd_filename) :
form.dive_ctd.data = d.ctd_filename
# NOT WORKING
if os.path.isfile(csvfiles_path+'/'+d.posiview_filename) :
form.dive_posiview.data = d.posiview_filename
return render_template('dive_new.html',title='edit dive',form = form , diveId = diveId)
except Exception as e:
flash(e)
return render_template("500.html")
the versions that I am using are :
Python 3.8.2
Flask 1.1.1
Flask-Uploads 0.2.1
Flask-WTF 0.14.3
WTForms 2.3.1
Thanks for the help
Related
Learning python flask and WTF. Been working on the code below based of the documentation and tutorials however cannot seem to locate the error.
Controller.py
from flask import Flask, escape, request, render_template, url_for, flash, redirect, send_from_directory, json, jsonify
from flask_wtf import FlaskForm
from wtforms import (StringField, PasswordField, SubmitField, BooleanField, DateTimeField,
RadioField, SelectField, TextField, TextAreaField, SubmitField)
from wtforms.validators import DataRequired, Length, Email, EqualTo
from form import infoForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdfghjklqwertyuiop1234567890'
#app.route('/test', methods=['GET','POST'])
def test():
breed = False
form = infoForm()
if form.validate_on_submit():
session['breed'] = form.breed.data
session['neutered'] = form.neutered.data
session['mood'] = form.mood.data
session['food_option'] = form.food_option.data
# breed = form.breed.data
# form.breed.data = ''
# return render_template('test.html', form = form, breed = breed)
return redirect(url_for('/'))
return render_template('test.html', form = form)
forms.py
class infoForm(FlaskForm):
# Used by forms.py essentially
breed = StringField("What breed are you?", validators = [DataRequired()])
neutered = BooleanField("Have you been neutered?"), choices = ['Yes'])
mood = RadioField('Please choose your mood: '),choices = [('mood_one','Happy'), ('mood_2','Sad')]
food_option = SelectField(u'Pick your fav food: '), choices = [('chic','Chicken') , ('bf','beef') , ('fish','fish')])
submit = SubmitField('Submit')
Response I get on my terminal is:
Traceback (most recent call last):
File "/Users/himanshu/Documents/MasterInt/HMSpython/controller.py", line 21, in <module>
from form import infoForm
File "/Users/himanshu/Documents/MasterInt/HMSpython/form.py", line 22
food_option = SelectField(u'Pick your fav food: ', choices = [('chic','Chicken') , ('bf','beef') , ('fish','fish')])
^
The arrow is under - after the word 'chic',
Would like to understand where am I going wrong as I did follow the documentation?
Thank you!
You got closing parenthesis ')' in wrong place on radiofields and booleanfield. You close the parenthesis before choices. Maybe that's the problem.
And put a space after comma, not before.
You can see what i mean down below.
class infoForm(FlaskForm):
# Used by forms.py essentially
breed = StringField("What breed are you?", validators=[DataRequired()])
neutered = BooleanField("Have you been neutered?", choices=['Yes'])
mood = RadioField('Please choose your mood:', choices=[('mood_one', 'Happy'), ('mood_2', 'Sad')])
food_option = SelectField(u'Pick your fav food:', choices=[('chic', 'Chicken'), ('bf', 'beef'), ('fish', 'fish')])
submit = SubmitField('Submit')
Python code: (the main_
...
from flask import Flask, render_template, url_for,request,flash,redirect
from formzxc import Amount
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = '8ed085d7c0aefb62c65e9d2154c3f377'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///testing.db'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
class Category(db.Model):
id = db.Column(db.Integer,primary_key = True)
desc = db.Column(db.String(25),unique = True,nullable =False)
amt = db.Column(db.Integer,nullable =False)
def __repr__(self):
return f"Category('{self.desc}'.'{self.amt}')"
#app.route('/',methods = ['GET','POST']) #need to research more on the methods
#app.route('/main',methods = ['GET','POST'])
def home():
form = Amount() #this is the amount FlaskForm imported
if form.validate_on_submit(): #validation is true
flash(f'Done liao','success') #a message to put; put at homepage or prev page
newpost = Category(desc = Amount.purpose.data,amt =Amount.amount.data ) ##
db.session.add(newpost)
db.session.commit()
return redirect(url_for('home')) #function
else:
flash('Shit!','danger')
return render_template(f'test.html',form = form)
if __name__ == '__main__':
app.run(debug=True)
....
Python code(for formzxc)
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField,IntegerField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class Amount(FlaskForm):
purpose = StringField('Type:',
validators = [DataRequired(),Length(max =25)])
amount = IntegerField('Amount:',
validators = [DataRequired()])
submit = SubmitField('Submit!')
fix bellow error
newpost = Category(desc = Amount.purpose.data,amt =Amount.amount.data )
change to
newpost = Category(desc = form.purpose.data,amt =form.amount.data )
because ur are passing FlaskForm object to Amount class when creating it Amount class inherited the object form from it.So u have to use that object to get the data.
I'm developing my app on Windows with GAE, but the below error message was shown.
C:\Python27\Lib\site-packages
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
So I checked some post in this site and I found some articles but I could not understand it. My understanding is that I need to create cache directory with write access in home directory, but I did not understand where "home directory" is.
Also in other post, I found the answer saying This approach solved my issue. I did uninstall pyyaml using pip and then installed it with easy_install -z pyyaml
Which approach is correct?
import webapp2
import os
import jinja2
import cloudstorage
import mimetypes
from PIL import Image
from google.appengine.ext import ndb
from google.appengine.ext import blobstore
from google.appengine.api import users
from google.appengine.api import app_identity
from google.appengine.api import images
from models import Note
from models import CheckListItem
from models import NoteFile
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
images_formats = {
'0':'image/png',
'1':'image/jpeg',
'2':'image/webp',
'-1':'image/bmp',
'-2':'image/gif',
'-3':'image/ico',
'-4':'image/tiff',
}
class MainHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user is not None:
logout_url = users.create_logout_url(self.request.uri)
template_context = {
'user': user.nickname(),
'logout_url' : logout_url,
}
template = jinja_env.get_template('main.html')
self.response.out.write(template.render(template_context))
else:
login_url = users.create_login_url(self.request.uri)
self.redirect(login_url)
def post(self):
user = users.get_current_user()
if user is None:
self.error(401)
bucket_name = app_identity.get_default_gcs_bucket_name()
uploaded_file = self.request.POST.get('uploaded_file')
file_name = getattr(uploaded_file,'filename',None)
file_content = getattr(uploaded_file,'file',None)
real_path = ''
if file_name and file_content:
content_t = mimetypes.guess_type(file_name)[0]
real_path = '/' + bucket_name + '/' + user.user_id() + "/" + file_name
with cloudstorage.open(real_path,'w',content_type=content_t,options={'x-goog-acl':'public-read'}) as f:
f.write(file_content.read())
self._create_note(user, file_name, real_path)
logout_url = users.create_logout_url(self.request.uri)
template_context = {
'user':user.nickname(),
'logout_url': logout_url,
}
self.response.out.write(self._render_template('main.html',template_context))
def _render_template(self,template_name,context=None):
if context is None:
context = {}
user = users.get_current_user()
ancestor_key = ndb.Key("User",user.nickname())
qry = Note.owner_query(ancestor_key)
context['notes'] = qry.fetch()
template = jinja_env.get_template(template_name)
return template.render(context)
#ndb.transactional
def _create_note(self,user,file_name,file_path):
note = Note(parent=ndb.Key("User", user.nickname()), title=self.request.get('title'), content=self.request.get('content'))
note.put()
item_titles = self.request.get('checklist_items').split(',')
for item_title in item_titles:
item = CheckListItem(parent=note.key, title=item_title)
item.put()
note.checklist_items.append(item.key)
if file_name and file_path:
url, thumbnail_url = self._get_urls_for(file_name)
f = NoteFile(parent=note.key, name=file_name, url=url,thumbnail_url=thumbnail_url,full_path=file_path)
f.put()
note.files.append(f.key)
note.put()
def _get_urls_for(self,file_name):
user = users.get_current_user()
if user is None:
return
bucket_name = app_identity.get_default_gcs_bucket_name()
path = '/' + bucket_name + '/' + user.user_id() + '/' + file_name
real_path = '/gs' + path
key = blobstore.create_gs_key(real_path)
try:
url = images.get_serving_url(key, size=0)
thumbnail_url = images.get_serving_url(key,size=150,crop=True)
except images.TransformationError,images.NotImageError:
url = "http://storage.googleapis.com{}".format(path)
thumbnail_url = None
return url,thumbnail_url
class MediaHandler(webapp2.RequestHandler):
def get(self,file_name):
user = users.get_current_user()
bucket_name = app_identity.get_default_gcs_bucket_name()
content_t = mimetypes.guess_type(file_name)[0]
real_path = '/' + bucket_name + '/' + user.user_id() + '/' + file_name
try:
with cloudstorage.open(real_path,'r')as f:
self.response.headers.add_header('Content-Type',content_t)
self.response.out.write(f.read())
except cloudstorage.errors.NotFoundError:
self.abort(404)
class ShrinkHandler(webapp2.RequestHandler):
def _shrink_note(self,note):
for file_key in note.files:
file = file_key.get() # this is the same as "file.get().url" in html file. we add the comment.
try:
with cloudstorage.open(file.full_path) as f:
image = images.Image(f.read())
image.resize(640)
new_image_data = image.execute_transforms()
content_t = images_format.get(str(image.format))
with cloudstorage.open(file.full_path,'w',content_type=content_t) as f:
f.write(new_image_data)
except images.NotImageError:
pass
def get(self):
user = users.get_current_user()
if user is None:
login_url = users.create_login_url(self.request.url)
return self.redirect(login_url)
ancestor_key = ndb.Key("User",user.nickname())
notes = Note.owner_query(ancestor_key).fetch()
for note in notes:
self._shrink_note(note)
self.response.write('Done.')
app = webapp2.WSGIApplication([
(r'/', MainHandler),
(r'/media/(?P<file_name>[\w.]{0,256})',MediaHandler),
(r'/shrink',ShrinkHandler)
], debug=True)
It looks like you're developing a standard env GAE app but you're attempting to install third party libraries in (and use them from) your local system's site packages. This won't work.
You need to install the third party libraries in your app's library directory (i.e. using -t <your_lib_dir> option for pip install, for which you shouldn't need special permissions. See also:
Using third-party libraries.
No module named warnings when starting GAE inside virtualenv locally
I'm having fun with flask and flask-appbuilder module and I have one problem which I can't resolve. I have this piece of code in my views.py:
from flask.ext.appbuilder import AppBuilder, BaseView, expose, has_access, SimpleFormView
from flask_appbuilder._compat import as_unicode
from app import appbuilder
from wtforms import Form, StringField, BooleanField, TextField, SelectMultipleField
from wtforms.validators import DataRequired
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget, DatePickerWidget
from flask.ext.appbuilder.forms import DynamicForm
from flask.ext.babelpkg import lazy_gettext as _
from wtforms.fields.html5 import DateField
from flask import flash, send_file, redirect, url_for
from scripts.create_excel import excelstuff
class MyView(BaseView):
default_view = 'method1'
#expose('/method1/')
#has_access
def method1(self):
# do something with param1
# and return to previous page or index
return 'Hello'
#expose('/method2/<string:param1>')
#has_access
def method2(self, param1):
# do something with param1
# and render template with param
param1 = 'Goodbye %s' % (param1)
return param1
#expose('/method3/<string:param1>')
#has_access
def method3(self, param1):
# do something with param1
# and render template with param
param1 = 'Goodbye %s' % (param1)
self.update_redirect()
return self.render_template('method3.html',
param1=param1)
#expose('/download/<string:filename>')
#has_access
def download(filename):
return send_file(appbuilder.app.config['UPLOAD_FOLDER'] + filename,
as_attachment=True)
# Forms
class MyForm(DynamicForm):
field1 = StringField(('Field1'),
description=('Your field number one!'),
validators=[DataRequired()], widget=BS3TextFieldWidget())
field2 = StringField(('Field2'),
description=('Your field number two!'), widget=BS3TextFieldWidget())
start = DateField('Start Date', format='%Y-%m-%d', validators=[DataRequired()], widget=DatePickerWidget())
end = DateField('Start Date', format='%Y-%m-%d', validators=[DataRequired()], widget=DatePickerWidget())
project1 = SelectMultipleField('Projects', choices=[('1', 'Choice1'), ('2', 'Choice2'), ('3', 'Choice3')],
coerce=unicode, validators=[DataRequired()])
username = StringField('Username', validators=[DataRequired()], widget=BS3TextFieldWidget())
class MyFormView(SimpleFormView):
default_view = 'this_form_get'
form = MyForm
form_title = 'This is my first form view'
message = 'My form submitted'
def form_post(self, form):
# process form
flash(as_unicode(form.field1.data), 'info')
excelstuff(as_unicode(form.field1.data))
return redirect(url_for('myview.download', filename='demo.xlsx'))
appbuilder.add_view(MyFormView, "My form View", icon="fa-group", label=_('My form View'),
category="My Forms", category_icon="fa-cogs")
appbuilder.add_view(MyView, "Method1", category='My View')
appbuilder.add_link("Method2", href='/myview/method2/john', category='My View')
appbuilder.add_link("Method3", href='/myview/method3/john', category='My View')
I sending my form and I executing another python function which creates an xls file with content sent by the form, but I don't know how can I do to redirect to this xls file and download it, this is the specific piece of code:
def form_post(self, form):
# process form
flash(as_unicode(form.field1.data), 'info')
excelstuff(as_unicode(form.field1.data))
return redirect(url_for('myview.download', filename='demo.xlsx'))
You have two problems.
1 - url_for is casesensitive, so do it like this:
return redirect(url_for('MyView.download', filename='demo.xlsx'))
2 - SimpleFormView.form_post is just for form processing the answer is made by the framework, so in this case you should override 'this_form_post'
#expose("/form", methods=['POST'])
#has_access
def this_form_post(self):
self._init_vars()
form = self.form.refresh()
if form.validate_on_submit():
flash(as_unicode(form.field1.data), 'info')
excelstuff(as_unicode(form.field1.data))
return redirect(url_for('MyView.download', filename='demo.xlsx'))
else:
widgets = self._get_edit_widget(form=form)
return self.render_template(
self.form_template,
title=self.form_title,
widgets=widgets,
appbuilder=self.appbuilder
)
I Have not tested it, tell me if it worked.
Hi I am trying to insert data to the database in django without forms.
This is my views.py file
def updatetrans(request):
json_data=open('/home/ttt/Abc/a.json').read()
data = json.loads(json_data)
for pk, pv in data.iteritems():
for k,v in pv.iteritems():
try:
print k, " =>> ", pv['transcript'][1]
except:
pass
This is my url.py file
url(r'^updatetrans/$', 'booki.account.views.updatetrans', name='updatetrans'),
Here is my models.py file. I have created two tables. And want to insert data in both of them separately.
class TransType(models.Model):
name = models.TextField()
def __unicode__(self):
return self.name
class Trans(models.Model):
trans = models.ForeignKey(TransType)
script = models.CharField(max_length=200)
def __unicode__(self):
return self.trans
I am getting the output on console. That output I want to save to the database.
Plz help.
Thank you.. I tried some other way. I am getting error as:
global name 'TransType' is not defined
Not inserted ==> e
My code:
def updatetrans(request):
json_data=open('/home/ttt/Ali/a.json').read()
data = json.loads(json_data)
for pk, pv in data.iteritems():
for k,v in pv.iteritems():
try:
trans_type = TransType.objects.get_or_create(name=k)
trans = Trans()
trans.trans_id = trans_type.id
trans.script = pv[k][1]
trans.save()
print " Inserted ==>", pv[k][1]
except Exception, e:
print e
print "Not inserted ==>", pv[k][1]
pass
return HttpResponse("Done")
The problem is solved. The answer is as follows.
To Store the records in the django database without using any input or form.
To avoid duplicate entries in the database.
This is my views.py file
def updatetrans(request):
json_data=open('/home/ttt/Ali/a.json').read()
data = json.loads(json_data)
for pk, pv in data.iteritems():
for k,v in pv.iteritems():
try:
trans_type = TransType.objects.get_or_create(name=k)
trans = Trans()
trans.transtype_id = trans_type[0].id
if isinstance(pv[k], basestring):
script = pv[k]
else:
print "****** List ****"
script = pv[k][1]
trans.script = script
trans.save()
print " Inserted ==>", script
except Exception, e:
print e
#print "Not inserted ==>", pv[k][1]
pass
return HttpResponse("Done")
This is my models.py file.
class TransType(models.Model):
name = models.TextField()
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
def __unicode__(self):
return self.name
class Trans(models.Model):
transtype = models.ForeignKey(TransType)
script = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
class Meta:
unique_together = (("transtype", "script"),)
def __unicode__(self):
return self.trans
You just want to save data to database, so you can do it like this easily
>> cd project_directory
>> python manage.py shell
>> from xxx.models import TransType,Trans
>> tt = TransType.objects.create(name='read from file')
>> Trans.objects.create(trans=tt, script='read from file')
or write a python script to import data to database, put it in your project directory,run python manage.py shell then import yourscript
if you don't like python manage.py shell, just set DJANGO_SETTINGS_MODULE environment, then just run python yourscript in terminal. Such as
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "yoursite.settings"
# The above two lines could be written simply as:
# from project.wsgi import *
from xxx.models import import TransType,Trans
TransType.objects.create()
Trans.objects.create()
remember to replace xxx with your app name
see QuerySet API:https://docs.djangoproject.com/en/dev/ref/models/querysets/#create
Chinese people could see here (other people could just read the code): http://www.ziqiangxuetang.com/django/django-import-data.html
You can do it using Model.objects.create()
Let's say you're receiving data from post form and want to save in QuillModel, here's how to do it in python2 django
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import redirect, render
from .forms import TemplateForm
from .models import QuillModel
def app3(request):
if request.method == "POST":
print(request.POST)
html_content = request.POST.get('html_content')
input_area = request.POST.get('input_area')
if html_content and input_area:
obj = QuillModel.objects.create(html_content=html_content, input_area=input_area)
obj.save()
return redirect('/app3/app3')
else:
form = TemplateForm()
return render(request, 'app3/forms/f1_post_form.html', {'form' : form})
See the if request.method == "POST": part for saving into database.
Since I have been doing the same thing..
For example:
models.py
class Dataset(models.Model):
hash = models.CharField(max_length=32)
category = models.CharField(max_length=10)
views.py
if request.method == "POST":
uploaded_file = request.FILES['document']
fs = FileSystemStorage()
fs.save(uploaded_file.name,uploaded_file)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
media_path = os.path.join(BASE_DIR,'dataset')
full_path=os.path.join(media_path,uploaded_file.name)
f = default_storage.open(full_path, 'r')
data = f.read()
for i in data.split("\n"):
hash,category = i.strip("\n").split(",")
Dataset.objects.create(hash=hash,category=category)
print("yes")
f.close()
Conclusion
You just specify your models and then create with what variable or column that you have.
MODELS.objects.create(column1=data1,column2=data2)
Example inside of my file
12345678,good
12345678,bad