[N] UC Berkeley Open-Sources 100k Driving Video Database
https://medium.com/@Synced/uc-berkeley-open-sources-100k-driving-video-database-dce09ff7cf78
/r/MachineLearning
https://redd.it/8ns7vv
https://medium.com/@Synced/uc-berkeley-open-sources-100k-driving-video-database-dce09ff7cf78
/r/MachineLearning
https://redd.it/8ns7vv
Medium
UC Berkeley Open-Sources 100k Driving Video Database
UC Berkeley’s Artificial Intelligence Research Lab (BAIR) has open-sourced their newest driving database, BDD100K, which contains over…
[AF]Why is my flask/SQLAlchemy simple app not respecting data constraints from db.Column parameters?
Hi.
I feel like this is more of SQLAlchemy question but I would assume that a lot of people here have used it as well in their Flask app, so this is why I'm asking here.
(Whole code at the end of the post)
The way I understand it, when creating the db using SQLAlchemy, we define the data that should be accepted by this column of the database using db.Column, for example:
field0 = db.Column("f0", db.String(3), unique=False, nullable=False, primary_key=True)
Here, the **field0** column is named *f0*, should accept only *string* data that is at most *3* characters long, should accept *non-unique* entries, but should not accept *empty* inputs.
However, once I run my app, I can enter literally anything into the respective columns, regardless of the constrains imposed during creation of the db.
So, either I did something wrong, or I don't understand how this whole thing should work.
I do understand that the db is defined the moment we create it, and not the moment the app is started. I made sure to create a fresh db with the correct column definitions.
**the_app.py**
____________________________
import os, datetime
from flask import Flask, Markup, render_template, request
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
database_file_uri = "sqlite:///{}".format(os.path.join(project_dir, "databse.db"))
app.config["SQLALCHEMY_DATABASE_URI"] = database_file_uri
db = SQLAlchemy(app)
class MyTable(db.Model):
field0 = db.Column("f0", db.String(3), unique=False, nullable=False, primary_key=True)
field1 = db.Column("f1", db.Integer, unique=False, nullable=False, primary_key=True)
def __repr__(self):
return " string representation".format(self.title)
def __init__(self, field0=field0, field1=field1):
self.field0 = field0
self.field1 = field1
@app.route("/", methods=["GET", "POST"])
def home():
if request.form:
newRow = MyTable(field0 = request.form.get("f0"), field1 = request.form.get("f1"))
db.session.add(newRow)
db.session.commit()
data_from_db = MyTable.query.all()
return render_template("home.html", data_from_db=data_from_db)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
**templates\home.html**
____________________________
<html>
<body>
<h1>Add entry</h1>
<form method="POST" action="/">
<input type="text" name="f0">
<input type="text" name="f1">
<input type="submit" value="Add">
</form>
<h1>Values</h1>
{% for elem in data_from_db %}
<p>{{elem.field0}} - {{elem.field1}}</p>
{% endfor %}
</body>
</html>
**db initialization**
____________________________
from the_app import db
db.create_all()
exit()
To recap, column constraints:
field0 = db.Column("f0", db.String(3), unique=False, nullable=False, primary_key=True)
field1 = db.Column("f1", db.Integer, unique=False, nullable=False, primary_key=True)
But, when I run the app and go to http://localhost:8080/, I am:
- able to insert very long strings into field0 (greater in length than 3)
- able to insert strings into field1 (which should only accept integers)
- able to insert empty fields (despite nullable=False)
- unable to insert identical fields (despite unique=False)
Can someone explain why db seems to just completely ignore the column constrains I'm using? Thanks for any replies in advance.
/r/flask
https://redd.it/8o0mfd
Hi.
I feel like this is more of SQLAlchemy question but I would assume that a lot of people here have used it as well in their Flask app, so this is why I'm asking here.
(Whole code at the end of the post)
The way I understand it, when creating the db using SQLAlchemy, we define the data that should be accepted by this column of the database using db.Column, for example:
field0 = db.Column("f0", db.String(3), unique=False, nullable=False, primary_key=True)
Here, the **field0** column is named *f0*, should accept only *string* data that is at most *3* characters long, should accept *non-unique* entries, but should not accept *empty* inputs.
However, once I run my app, I can enter literally anything into the respective columns, regardless of the constrains imposed during creation of the db.
So, either I did something wrong, or I don't understand how this whole thing should work.
I do understand that the db is defined the moment we create it, and not the moment the app is started. I made sure to create a fresh db with the correct column definitions.
**the_app.py**
____________________________
import os, datetime
from flask import Flask, Markup, render_template, request
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
database_file_uri = "sqlite:///{}".format(os.path.join(project_dir, "databse.db"))
app.config["SQLALCHEMY_DATABASE_URI"] = database_file_uri
db = SQLAlchemy(app)
class MyTable(db.Model):
field0 = db.Column("f0", db.String(3), unique=False, nullable=False, primary_key=True)
field1 = db.Column("f1", db.Integer, unique=False, nullable=False, primary_key=True)
def __repr__(self):
return " string representation".format(self.title)
def __init__(self, field0=field0, field1=field1):
self.field0 = field0
self.field1 = field1
@app.route("/", methods=["GET", "POST"])
def home():
if request.form:
newRow = MyTable(field0 = request.form.get("f0"), field1 = request.form.get("f1"))
db.session.add(newRow)
db.session.commit()
data_from_db = MyTable.query.all()
return render_template("home.html", data_from_db=data_from_db)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
**templates\home.html**
____________________________
<html>
<body>
<h1>Add entry</h1>
<form method="POST" action="/">
<input type="text" name="f0">
<input type="text" name="f1">
<input type="submit" value="Add">
</form>
<h1>Values</h1>
{% for elem in data_from_db %}
<p>{{elem.field0}} - {{elem.field1}}</p>
{% endfor %}
</body>
</html>
**db initialization**
____________________________
from the_app import db
db.create_all()
exit()
To recap, column constraints:
field0 = db.Column("f0", db.String(3), unique=False, nullable=False, primary_key=True)
field1 = db.Column("f1", db.Integer, unique=False, nullable=False, primary_key=True)
But, when I run the app and go to http://localhost:8080/, I am:
- able to insert very long strings into field0 (greater in length than 3)
- able to insert strings into field1 (which should only accept integers)
- able to insert empty fields (despite nullable=False)
- unable to insert identical fields (despite unique=False)
Can someone explain why db seems to just completely ignore the column constrains I'm using? Thanks for any replies in advance.
/r/flask
https://redd.it/8o0mfd
reddit
r/flask - [AF]Why is my flask/SQLAlchemy simple app not respecting data constraints from db.Column parameters?
3 votes and 1 so far on reddit
Flask SQLAlchemy tenant data isolation
hello,
I'm currently moving my flask application from a multi instance to multi-tenant architecture. I want to isolate customer data to its own db rather than comingle it with context in a single db. I have found a couple of learning resources so far, like this bit on using binds for table isolation
SQLALCHEMY_DATABASE_URI = 'postgres://localhost/main'
SQLALCHEMY_BINDS = {
'users': 'mysqldb://localhost/users',
'appmeta': 'sqlite:////path/to/appmeta.db'
}
[Source](http://flask-sqlalchemy.pocoo.org/2.3/binds/#binds)
My trouble is whether this is the best way of isolation. I'm wondering how to update the binds and inject the new database URI as the application gains new tenants. The best resource I've found is
[this talk](https://www.infoq.com/presentations/saas-python).
I'm wondering if someone can help point me towards learning resources or help me ask this question in a better way because I'm stuck.
/r/flask
https://redd.it/8o15hq
hello,
I'm currently moving my flask application from a multi instance to multi-tenant architecture. I want to isolate customer data to its own db rather than comingle it with context in a single db. I have found a couple of learning resources so far, like this bit on using binds for table isolation
SQLALCHEMY_DATABASE_URI = 'postgres://localhost/main'
SQLALCHEMY_BINDS = {
'users': 'mysqldb://localhost/users',
'appmeta': 'sqlite:////path/to/appmeta.db'
}
[Source](http://flask-sqlalchemy.pocoo.org/2.3/binds/#binds)
My trouble is whether this is the best way of isolation. I'm wondering how to update the binds and inject the new database URI as the application gains new tenants. The best resource I've found is
[this talk](https://www.infoq.com/presentations/saas-python).
I'm wondering if someone can help point me towards learning resources or help me ask this question in a better way because I'm stuck.
/r/flask
https://redd.it/8o15hq
A game of tokens: write an interpreter in Python with TDD - Part 4
http://blog.thedigitalcatonline.com/blog/2018/06/02/a-game-of-tokens-write-an-interpreter-in-python-with-tdd-part-4/
/r/Python
https://redd.it/8o0o8h
http://blog.thedigitalcatonline.com/blog/2018/06/02/a-game-of-tokens-write-an-interpreter-in-python-with-tdd-part-4/
/r/Python
https://redd.it/8o0o8h
reddit
r/Python - A game of tokens: write an interpreter in Python with TDD - Part 4
3 votes and 0 so far on reddit
how to use a variable in a template other than via : return render_template('template.html',variable=variable)
my program currently look like this and is becoming more and more unreadable as i need to display things from my database in my template because i dont know how to do it other than this currently
app= Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'database1'
mysql = MySQL(app)
@app.route('/1')
def route1():
var=function_getting_something_from_database(mysql)
var2=function_getting_something_else_from_database(mysql)
var3=other_function_getting_something_from_database(mysql)
(...)
return render_template('home.html',variable=var,variable2=var2,variable3=var3)
@app.route('/2')
def route2():
var=some_function_getting_something_from_database(mysql)
var2=function_getting_something_else_from_database(mysql)
var3=other_function_getting_something_from_database(mysql)
(...)
return render_template('home.html',variable=var,variable2=var2,variable3=var3)
if ((__name__) == '__main__'):
app.run()
home.html
<p>{{ variable }}</p>
<p>{{ variable2 }}</p>
<p>{{ variable3 }}</p>
/r/flask
https://redd.it/8nzwsb
my program currently look like this and is becoming more and more unreadable as i need to display things from my database in my template because i dont know how to do it other than this currently
app= Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'database1'
mysql = MySQL(app)
@app.route('/1')
def route1():
var=function_getting_something_from_database(mysql)
var2=function_getting_something_else_from_database(mysql)
var3=other_function_getting_something_from_database(mysql)
(...)
return render_template('home.html',variable=var,variable2=var2,variable3=var3)
@app.route('/2')
def route2():
var=some_function_getting_something_from_database(mysql)
var2=function_getting_something_else_from_database(mysql)
var3=other_function_getting_something_from_database(mysql)
(...)
return render_template('home.html',variable=var,variable2=var2,variable3=var3)
if ((__name__) == '__main__'):
app.run()
home.html
<p>{{ variable }}</p>
<p>{{ variable2 }}</p>
<p>{{ variable3 }}</p>
/r/flask
https://redd.it/8nzwsb
reddit
r/flask - how to use a variable in a template other than via : return render_template('template.html',variable=variable)
2 votes and 7 so far on reddit
[N] Google Will Not Renew Project Maven Contract
https://www.nytimes.com/2018/06/01/technology/google-pentagon-project-maven.html
/r/MachineLearning
https://redd.it/8o0j19
https://www.nytimes.com/2018/06/01/technology/google-pentagon-project-maven.html
/r/MachineLearning
https://redd.it/8o0j19
NY Times
Google Will Not Renew Pentagon Contract That Upset Employees (Published 2018)
Diane Greene, the head of Google’s Cloud business, is said to have told employees that it was backing away from the A.I. work with the military.
Very Peculiar Flask Issue
Hey guys. I'm really confused.
I'm trying to open a URL in Flask in an embedded browser (X-Frame), the problem is the URL is not allowed to be opened in the X-Frame so comes up blank.
What I'm trying to do (very unsuccesfully) is simply just redirect from the embedded page to the regular version (non-embedded) of the billing page I want to visit.
When I put in the URL of the billing page manually into the browser, it works fine.
Any thoughts as to how to get this to work WITHOUT opening a new tab?
/r/flask
https://redd.it/8nw952
Hey guys. I'm really confused.
I'm trying to open a URL in Flask in an embedded browser (X-Frame), the problem is the URL is not allowed to be opened in the X-Frame so comes up blank.
What I'm trying to do (very unsuccesfully) is simply just redirect from the embedded page to the regular version (non-embedded) of the billing page I want to visit.
When I put in the URL of the billing page manually into the browser, it works fine.
Any thoughts as to how to get this to work WITHOUT opening a new tab?
/r/flask
https://redd.it/8nw952
reddit
r/flask - Very Peculiar Flask Issue
5 votes and 8 so far on reddit
Any Django 2.0 tutorials?
I went through the docs but I still don't feel like good at Django. I've been trying to find some other resources but all of them weren't on 2.0 and did things differently than what I learnt. Any resources you would recommend?
/r/django
https://redd.it/8o3p8g
I went through the docs but I still don't feel like good at Django. I've been trying to find some other resources but all of them weren't on 2.0 and did things differently than what I learnt. Any resources you would recommend?
/r/django
https://redd.it/8o3p8g
reddit
r/django - Any Django 2.0 tutorials?
9 votes and 3 so far on reddit
Django Celery Periodic Task at specific time
I asked a question on stackoverflow. [this](https://stackoverflow.com/questions/50649919/django-celery-periodic-task-at-specific-time) is the link to the question.
Complete Question:
I am using `celery==4.1.1` in my project. In my `settings.py`, I have the following:
from celery.schedules import crontab
CELERY_BROKER_URL = "redis://127.0.0.1:6379/1"
CELERY_TIMEZONE = 'Asia/Kolkata'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/1"
CELERY_BEAT_SCHEDULE = {
'task-number-one': {
'task': 'mathematica.core.tasks.another_test',
'schedule': crontab(minute=45, hour=00)
},
'task-number-two': {
'task': 'mathematica.core.tasks.test',
'schedule': crontab(hour='*/1')
}
}
The second task mentioned in `CELERY_BEAT_SCHEDULE` is running perfectly. However, the first task `mathematica.core.tasks.another_test` which is a simple function returning a string is not running at the specified time, `00:45 (45 minutes past midnight)`. I have tried a number of ways to run a function at a given time each day but failed to achieve the same.
Please suggest ways/hints to achieve the same results.
Edit:
My test function looks like the following
from celery import task
@task
def another_test():
return "another test"
/r/djangolearning
https://redd.it/8o1hvq
I asked a question on stackoverflow. [this](https://stackoverflow.com/questions/50649919/django-celery-periodic-task-at-specific-time) is the link to the question.
Complete Question:
I am using `celery==4.1.1` in my project. In my `settings.py`, I have the following:
from celery.schedules import crontab
CELERY_BROKER_URL = "redis://127.0.0.1:6379/1"
CELERY_TIMEZONE = 'Asia/Kolkata'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/1"
CELERY_BEAT_SCHEDULE = {
'task-number-one': {
'task': 'mathematica.core.tasks.another_test',
'schedule': crontab(minute=45, hour=00)
},
'task-number-two': {
'task': 'mathematica.core.tasks.test',
'schedule': crontab(hour='*/1')
}
}
The second task mentioned in `CELERY_BEAT_SCHEDULE` is running perfectly. However, the first task `mathematica.core.tasks.another_test` which is a simple function returning a string is not running at the specified time, `00:45 (45 minutes past midnight)`. I have tried a number of ways to run a function at a given time each day but failed to achieve the same.
Please suggest ways/hints to achieve the same results.
Edit:
My test function looks like the following
from celery import task
@task
def another_test():
return "another test"
/r/djangolearning
https://redd.it/8o1hvq
Stack Overflow
Django Celery Periodic Task at specific time
I am using celery==4.1.1 in my project. In my settings.py, I have the following:
from celery.schedules import crontab
CELERY_BROKER_URL = "redis://127.0.0.1:6379/1"
CELERY_TIMEZONE = 'Asia/Kolkata'
from celery.schedules import crontab
CELERY_BROKER_URL = "redis://127.0.0.1:6379/1"
CELERY_TIMEZONE = 'Asia/Kolkata'
Animate points in two numpy arrays with matplotlib
hi,
i have two numpy arrays X and Y with same length describing a circumference. The points are created with a function that takes as inputs the radius and the number of points i want and return the already mentioned X and Y arrays.
i want a animation to show 1 pair of points at the time but i have not being able to achieve this using matplotlib. i would show my animation code but truly is useless garbage. Can you guys please point me in the right direction on how to make this work?
Thanks.
/r/IPython
https://redd.it/8o5vft
hi,
i have two numpy arrays X and Y with same length describing a circumference. The points are created with a function that takes as inputs the radius and the number of points i want and return the already mentioned X and Y arrays.
i want a animation to show 1 pair of points at the time but i have not being able to achieve this using matplotlib. i would show my animation code but truly is useless garbage. Can you guys please point me in the right direction on how to make this work?
Thanks.
/r/IPython
https://redd.it/8o5vft
reddit
r/IPython - Animate points in two numpy arrays with matplotlib
1 votes and 0 so far on reddit
Can I use a value from a foreign key in the __string__ of a model?
Edit: I mean the \_\_str\_\_ method. Not \_\_string\_\_
I have an mailing address table that has a foreign key to a User. On the admin page, when I'm looking at the list of Addresses, instead of saying "Address Object" I'd like it to say something like "John Smith: 1234 SomeStreet".
When defining the Address model can I access the name from the User model? Or do I need to have a name field in the Address that duplicates the users name?
/r/djangolearning
https://redd.it/8nvlzx
Edit: I mean the \_\_str\_\_ method. Not \_\_string\_\_
I have an mailing address table that has a foreign key to a User. On the admin page, when I'm looking at the list of Addresses, instead of saying "Address Object" I'd like it to say something like "John Smith: 1234 SomeStreet".
When defining the Address model can I access the name from the User model? Or do I need to have a name field in the Address that duplicates the users name?
/r/djangolearning
https://redd.it/8nvlzx
reddit
r/djangolearning - Can I use a value from a foreign key in the __string__ of a model?
2 votes and 2 so far on reddit
ML - Linear & Logistic Regression, K Means, Decision Trees & Random Forests easily explained in Python
https://www.youtube.com/watch?v=0kH6-Bafrto&list=PL998lXKj66MrJc80jS0E1htuEo5zI-tYG
/r/Python
https://redd.it/8o34n9
https://www.youtube.com/watch?v=0kH6-Bafrto&list=PL998lXKj66MrJc80jS0E1htuEo5zI-tYG
/r/Python
https://redd.it/8o34n9
YouTube
Practical Machine Learning Tutorial
What is Machine Learning?
Can we train a machine to distinguish a cat from a dog? We will start with an overview of machine learning and its applications, then we will look at the various machine learning algorithms which are broadly classified as supervised…
Can we train a machine to distinguish a cat from a dog? We will start with an overview of machine learning and its applications, then we will look at the various machine learning algorithms which are broadly classified as supervised…
Postgres JSONField how to validate?
I am trying to create a user profile schema for accounts and I have profile information stored in a separate table. In the profile schema there are some fields that are basically array of objects. For example, "experiences" is has a schema like this (array of objects):
[
{ title, employer, location, duration: { from, to } }
...
]
I am currently using JSONField to store these types of data but I want a way to validate the contents of the data. For example, I want to be able to check that when appending a new entry to JSON field, the mode validates that there are **only** "title", "employee", "location", and "duration" keys and "duration" key is an object with "from" and "to" keys.
I just need a way to define a function that can validate these fields.
/r/django
https://redd.it/8o1q3k
I am trying to create a user profile schema for accounts and I have profile information stored in a separate table. In the profile schema there are some fields that are basically array of objects. For example, "experiences" is has a schema like this (array of objects):
[
{ title, employer, location, duration: { from, to } }
...
]
I am currently using JSONField to store these types of data but I want a way to validate the contents of the data. For example, I want to be able to check that when appending a new entry to JSON field, the mode validates that there are **only** "title", "employee", "location", and "duration" keys and "duration" key is an object with "from" and "to" keys.
I just need a way to define a function that can validate these fields.
/r/django
https://redd.it/8o1q3k
reddit
r/django - Postgres JSONField how to validate?
9 votes and 10 so far on reddit
Best video resources for learning Django?
There are a lot of books for Django, but I learn better with videos. Are they any good and updated video tutorials?
/r/django
https://redd.it/8o7g57
There are a lot of books for Django, but I learn better with videos. Are they any good and updated video tutorials?
/r/django
https://redd.it/8o7g57
reddit
Best video resources for learning Django? • r/django
There are a lot of books for Django, but I learn better with videos. Are they any good and updated video tutorials?
Linking two separate django projects
I'm currently in the process of building my portfolio website. Although this site is mostly static I'm using django as the backend for it \(I have some plans to make it more backend heavy in the future\). I plan on making some small personal projects with django and then somehow linking them on my portfolio page.
My question is how can I link two separate django projects together? I dont want to buy a domain name and more server hosting for these small personal projects because I think thats a bit overkill and expensive. These projects are only examples of what I can do and serve as a placeholder until I get some real projects done.
I know you can create reuseable apps in django but I think it might get pretty messy trying to combine all these apps and their static files and databases into one app. Is this my best option? I don't mind hosting multiple apps on one VPS.
This is only going to be temporary, I'm hoping to get some real projects done which will then replace these personal ones.
Thanks guys
/r/django
https://redd.it/8o7t78
I'm currently in the process of building my portfolio website. Although this site is mostly static I'm using django as the backend for it \(I have some plans to make it more backend heavy in the future\). I plan on making some small personal projects with django and then somehow linking them on my portfolio page.
My question is how can I link two separate django projects together? I dont want to buy a domain name and more server hosting for these small personal projects because I think thats a bit overkill and expensive. These projects are only examples of what I can do and serve as a placeholder until I get some real projects done.
I know you can create reuseable apps in django but I think it might get pretty messy trying to combine all these apps and their static files and databases into one app. Is this my best option? I don't mind hosting multiple apps on one VPS.
This is only going to be temporary, I'm hoping to get some real projects done which will then replace these personal ones.
Thanks guys
/r/django
https://redd.it/8o7t78
reddit
r/django - Linking two separate django projects
1 votes and 0 so far on reddit
need some help with form creation
So I am trying to create a form on my site.
This form will take in 4 fields. 3 are textfields and one is a file field intended only for multiple picture uploads.
After doing some researching I decided that it would be best to create a model that would store what is gotten from this field? My main issue right now is 2 things
* validation of the inputs and saving the inputs
* printing out the pictures that were received from the uploads
I have looked at the django documentation but it doesnt make much sense to me, can anyone help me or point me to a repo somewhere else that has the pointers I need to be able to do what I want it to do? I'm a django noobie and lost on what I need to do next and unfortunately I find the django documentation, while vast in its knowledge, doesnt provide any working coding examples that I like to use to compare and contrast
My code below
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from documents.forms import ContactForm
from django.views.generic import TemplateView
def index(request):
print("constitution index")
return render(request, 'documents/constitution.html')
def policies(request):
print("policies index")
return render(request, 'documents/policies.html')
def photo_gallery(request):
if request.method == 'POST':
print("photo_gallery POST")
form = ContactForm(request.POST)
form.save()
title = form.cleaned_data['title']
additional_info = form.cleaned_data['additional_info']
print("additional_info=["+str(additional_info)+"]")
contact_info = form.cleaned_data['contact_info']
photos = request.FILES.getlist('pics_from_event')
if photos is not None:
for photo in photos:
print("photo=["+str(photo)+"]")
else:
print("no pictures detected")
else:
form = ContactForm()
args = {'form': form}
print("photo_gallery not POST")
return render(request, 'documents/photo_gallery.html', args)
def photos(request):
print("photo gallery index")
return render(request, 'documents/photo_gallery.html')
# Create your views here.
forms.py
from django import forms
from documents.models import Upload
class ContactForm(forms.ModelForm):
title = forms.CharField(required=True)
contact_info = forms.CharField(required=False)
additional_info = forms.CharField(required=False)
pics_from_event = forms.FileField(required=True,
widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = Upload
fields = ('title', 'contact_info', 'additional_info', 'pics_from_event' )
def save(self, commit=True):
upload = super(ContactForm, self).save(commit=False)
upload.title = self.cleaned_data['title']
upload.contact_info = self.cleaned_data['contact_info']
upload.additional_info = self.cleaned_data['additional_info']
if commit:
upload.save()
return upload
models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
def get_settings():
return {
'attachment_upload_to': getattr(
settings,
'USER_ATTACHMENT_UPLOAD_TO',
'UPLOAD_attachments/%Y/%m/%d/'
)
}
def get_attachment_save_path(instance, filename):
settings = get_settings()
path = settings['attachment_upload_to']
if '%' in path:
path = datetime.datetime.utcnow().strftime(path)
return os.path.join(
path,
filename,
)
class documentsPage(models.Model):
title=models.CharField(max_length=140)
body=models.TextField()
def __str__(self):
return self.title
# Create your models here.
class Upload(models.Model):
title = models.CharField(
_(u'title'),
max_length=255
)
contact_info = models.CharField(
_(u'title'),
max_length=255
)
additional_info = models.CharField(
_(u'title'),
max_length=255
)
message_id = models.CharField(
_(u'Message ID'),
max_length=255
)
class UploadAttachment(models.Model):
upload = models.ForeignKey(
Uplo
So I am trying to create a form on my site.
This form will take in 4 fields. 3 are textfields and one is a file field intended only for multiple picture uploads.
After doing some researching I decided that it would be best to create a model that would store what is gotten from this field? My main issue right now is 2 things
* validation of the inputs and saving the inputs
* printing out the pictures that were received from the uploads
I have looked at the django documentation but it doesnt make much sense to me, can anyone help me or point me to a repo somewhere else that has the pointers I need to be able to do what I want it to do? I'm a django noobie and lost on what I need to do next and unfortunately I find the django documentation, while vast in its knowledge, doesnt provide any working coding examples that I like to use to compare and contrast
My code below
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from documents.forms import ContactForm
from django.views.generic import TemplateView
def index(request):
print("constitution index")
return render(request, 'documents/constitution.html')
def policies(request):
print("policies index")
return render(request, 'documents/policies.html')
def photo_gallery(request):
if request.method == 'POST':
print("photo_gallery POST")
form = ContactForm(request.POST)
form.save()
title = form.cleaned_data['title']
additional_info = form.cleaned_data['additional_info']
print("additional_info=["+str(additional_info)+"]")
contact_info = form.cleaned_data['contact_info']
photos = request.FILES.getlist('pics_from_event')
if photos is not None:
for photo in photos:
print("photo=["+str(photo)+"]")
else:
print("no pictures detected")
else:
form = ContactForm()
args = {'form': form}
print("photo_gallery not POST")
return render(request, 'documents/photo_gallery.html', args)
def photos(request):
print("photo gallery index")
return render(request, 'documents/photo_gallery.html')
# Create your views here.
forms.py
from django import forms
from documents.models import Upload
class ContactForm(forms.ModelForm):
title = forms.CharField(required=True)
contact_info = forms.CharField(required=False)
additional_info = forms.CharField(required=False)
pics_from_event = forms.FileField(required=True,
widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = Upload
fields = ('title', 'contact_info', 'additional_info', 'pics_from_event' )
def save(self, commit=True):
upload = super(ContactForm, self).save(commit=False)
upload.title = self.cleaned_data['title']
upload.contact_info = self.cleaned_data['contact_info']
upload.additional_info = self.cleaned_data['additional_info']
if commit:
upload.save()
return upload
models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
def get_settings():
return {
'attachment_upload_to': getattr(
settings,
'USER_ATTACHMENT_UPLOAD_TO',
'UPLOAD_attachments/%Y/%m/%d/'
)
}
def get_attachment_save_path(instance, filename):
settings = get_settings()
path = settings['attachment_upload_to']
if '%' in path:
path = datetime.datetime.utcnow().strftime(path)
return os.path.join(
path,
filename,
)
class documentsPage(models.Model):
title=models.CharField(max_length=140)
body=models.TextField()
def __str__(self):
return self.title
# Create your models here.
class Upload(models.Model):
title = models.CharField(
_(u'title'),
max_length=255
)
contact_info = models.CharField(
_(u'title'),
max_length=255
)
additional_info = models.CharField(
_(u'title'),
max_length=255
)
message_id = models.CharField(
_(u'Message ID'),
max_length=255
)
class UploadAttachment(models.Model):
upload = models.ForeignKey(
Uplo
ad,
related_name='upload',
null=True,
blank=True,
verbose_name=_('upload'),
on_delete=models.CASCADE
)
document = models.FileField(
_(u'Document'),
upload_to=get_attachment_save_path,
)
/r/djangolearning
https://redd.it/8o7h66
related_name='upload',
null=True,
blank=True,
verbose_name=_('upload'),
on_delete=models.CASCADE
)
document = models.FileField(
_(u'Document'),
upload_to=get_attachment_save_path,
)
/r/djangolearning
https://redd.it/8o7h66
reddit
r/djangolearning - need some help with form creation
1 votes and 0 so far on reddit
Do you normally use string.format() or percentage (%) to format your Python strings?
There are two ways of string formatting in python and I've been consistently using the percentage (%) method until now:
"Today is %s." % datetime.now() # 2018-06-03 16:50:35.226194
"%d is a good number." % 5 # 5
I know this may not be very eloquent, but does the job well. One of the major irritants for me is the number to string conversion, I've faced that error so many times in the earlier days when I simply used to `"There are " + x + " mangoes."`. This works great in most other languages as they "auto-convert" the x from integer to string, but not python because of its "explicitness". But today, I learned of this new method of `string.format()` which does the same job, perhaps more eloquently:
"Today is {0}.".format(datetime.now()) # 2018-06-03 16:50:35.226194
"{0} is a good number.".format(5) # 5
The only problem I'd imagine would be when you have to deal with long floats:
f = 1.234535666
"this is a floating point number: {0}".format(f) # 1.234535666
Problem here is that it will output the entire float as it is without rounding, and here is where my percentage method has an edge!
"this is a floating point number: %.2f" % f # 1.23
/r/Python
https://redd.it/8o7yhi
There are two ways of string formatting in python and I've been consistently using the percentage (%) method until now:
"Today is %s." % datetime.now() # 2018-06-03 16:50:35.226194
"%d is a good number." % 5 # 5
I know this may not be very eloquent, but does the job well. One of the major irritants for me is the number to string conversion, I've faced that error so many times in the earlier days when I simply used to `"There are " + x + " mangoes."`. This works great in most other languages as they "auto-convert" the x from integer to string, but not python because of its "explicitness". But today, I learned of this new method of `string.format()` which does the same job, perhaps more eloquently:
"Today is {0}.".format(datetime.now()) # 2018-06-03 16:50:35.226194
"{0} is a good number.".format(5) # 5
The only problem I'd imagine would be when you have to deal with long floats:
f = 1.234535666
"this is a floating point number: {0}".format(f) # 1.234535666
Problem here is that it will output the entire float as it is without rounding, and here is where my percentage method has an edge!
"this is a floating point number: %.2f" % f # 1.23
/r/Python
https://redd.it/8o7yhi
reddit
Do you normally use string.format() or percentage (%)... • r/Python
There are two ways of string formatting in python and I've been consistently using the percentage (%) method until now: "Today is %s." %...
Need help in inputing scores from quiz into text files and creating a program to display the scores
I have created the quiz but just need a way to have every person doing the quiz complete it 3 times and save the scores on text files. There a total of 3 classes where I need a text file for each class. Finally I need a program where I can display the information of each class seperatley while choosing to display it in alphabetical order showing each students highest score,by the highest score in descending order and by the average score in descending order. I know this is alot to ask but I am currently just lost on how to do this.
The code https://imgur.com/a/qR54CAI
/r/Python
https://redd.it/8o8qbv
I have created the quiz but just need a way to have every person doing the quiz complete it 3 times and save the scores on text files. There a total of 3 classes where I need a text file for each class. Finally I need a program where I can display the information of each class seperatley while choosing to display it in alphabetical order showing each students highest score,by the highest score in descending order and by the average score in descending order. I know this is alot to ask but I am currently just lost on how to do this.
The code https://imgur.com/a/qR54CAI
/r/Python
https://redd.it/8o8qbv
[Book announcement] Building Multi Tenant Applications with Django - Details in comments
https://github.com/agiliq/building-multi-tenant-applications-with-django/
/r/django
https://redd.it/8o9l1g
https://github.com/agiliq/building-multi-tenant-applications-with-django/
/r/django
https://redd.it/8o9l1g
GitHub
GitHub - agiliq/building-multi-tenant-applications-with-django
Contribute to agiliq/building-multi-tenant-applications-with-django development by creating an account on GitHub.