Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
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
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
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
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
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
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
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
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
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
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
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
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
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
Social Groups in Django

Let's say I have an 'articles' app. A user who belongs to 'Group A' publishes an article. This article can only be read by the members of 'Group A.' 'Group A' also has a superuser but his permissions are only valid for users in 'Group A.' How would I go about implementing this?

/r/django
https://redd.it/8o9ysg
Super Beginner Python question.

Hi all,

I am currently programming some descriptive analytics on a CSV file.

I have imported using Pandas as far as I know.

My general aim; Create a bar chart of Location occurrence within the CSV file

The image below is as far as I have got but this is not all of the variables.

I am wondering if there is a way of importing the 'many' different locations as separate variables as I need to add 1 to each variable when the regex is matched against the CSV.

The CSV column is called; \(Some are abbreviated for ease as variables\)

**Borough**

>COL = 0
>
>Barnet = 0
>
>Bexley = 0
>
>BAD = 0
>
>Brent = 0
>
>Bromley = 0
>
>Camden = 0
>
>Croydon = 0
>
>Ealing = 0
>
>Enfield = 0
>
>Greenwich = 0
>
>Hackney = 0
>
>HAF = 0
>
>Haringey = 0
>
>Harrow = 0
>
>Havering = 0
>
>Hillingdon = 0
>
>Hounslow = 0
>
>Islington = 0
>
>KAC = 0
>
>KUT = 0
>
>Lambeth = 0
>
>Lewisham = 0
>
>Merton = 0
>
>Newham = 0
>
>Redbridge = 0
>
>RUT = 0
>
>Southwark = 0
>
>Sutton = 0
>
>TowerHamlets = 0
>
>WalthamForest = 0
>
>Wandsworth = 0
>
>Westminster = 0
>
>OuterBorough = 0
>
>InnerBorough = 0

Here is my current code with the output of the image below:

#Start of Imports
import csv
import sys
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
#End of Imports

#Start of Declarations
COL = 0
Barnet = 0
Bexley = 0
BAD = 0
Brent = 0
Bromley = 0
Camden = 0
Croydon = 0
Ealing = 0
#This is as far as I got when I thought something was wrong?
Enfield = 0
Greenwich = 0
Hackney = 0
HAF = 0
Haringey = 0
Harrow = 0
Havering = 0
Hillingdon = 0
Hounslow = 0
Islington = 0
KAC = 0
KUT = 0
Lambeth = 0
Lewisham = 0
Merton = 0
Newham = 0
Redbridge = 0
RUT = 0
Southwark = 0
Sutton = 0
TowerHamlets = 0
WalthamForest = 0
Wandsworth = 0
Westminster = 0
OuterBorough = 0
InnerBorough = 0
#End of Declarations

#Starts reading 'csv file'
csv = pd.read_csv ('land-area-population-density-london.csv') #Not sure what this does, index_col=3)

#Start of IF Statement
csva = np.array(csv)
for column in np.arange(0, csva.shape[0]):
if re.match(r"Barnet", str(csva[column][2])) is not None:
Barnet = Barnet + 1
elif re.match(r"Bexley", str(csva[column][2])) is not None:
Bexley = Bexley + 1
elif re.match(r"City of London", str(csva[column][2])) is not None:
COL = COL + 1
elif re.match(r"Barking and Dagenham", str(csva[column][2])) is not None:
BAD = BAD + 1
elif re.match(r"Brent", str(csva[column][2])) is not None:
Brent = Brent + 1
elif re.match(r"Bromley", str(csva[column][2])) is not None:
Bromley = Bromley + 1
elif re.match(r"Camden", str(csva[column][2])) is not None:
Camden = Camden + 1
elif re.match(r"Croydon", str(csva[column][2])) is not None:
Croydon = Croydon + 1
elif re.match(r"Ealing", str(csva[column][2])) is not None:
Ealing = Ealing + 1
#End of IF Statement

#Start of graph fields
#Below: Places is the labels for the placesvar
places = ('Barnet', 'Bexley', 'City of London', 'Barking and Dagenham', 'Brent', 'Bromley', 'Camden', 'Croydon', 'Ealing')
#Below: placesvar the actual 'places' pulled from CSV
placesvar = [Barnet, Bexley, COL, BAD, Brent, Bromley, Camden, Croydon, Ealing]
#Y Positioning numpy.arange (Again no idea what this does) length 'places pulled from csv'
y_pos = np.arange(len(placesvar))
#End of graph fields

#Start of Graph positions and Names
plt.bar(y_pos, placesvar, align='center')
plt.xticks(y_pos, places, rot