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
Update / Save model date value directly from template?

Hello all,

I am still quite inexperienced in Django and I was wondering if it would be at all possible to update/save today's date in my database directly from the template?

I have a Django-filter filterView (listView) that shows the list of people that are in my department which I currently have in my database. And I would like to update a datetime value (when the people have last been visited) to today's date by clicking on a <a><\a> link that shows in the list. That way I don't have to setup an update view just to update when I've last visited the coworkers. Is something like this even possible?

I did try to implement a function in my models.py with the @property tag but when I refresh the webpage, or visit the page it automatically updates it without having to click on the link.

Edit: Here is the code:

# models.py
@property
def update_visit_date(self):
self.last_visit = timezone.make_aware(datetime.datetime.today())
super(Directory, self).save()
return reverse('directory_list')

# snippet from my template directory_list.html
{% for contact in items %}
<tr>
<td>{{ contact.first_name }}</td>
<td>{{ contact.last_name }}</td>
<th><a href="{{ contact.get_absolute_url }}">{{ contact.email_address }}</a></th>
<td>{{ contact.phone_number_1 }}</td>
<td>{{ contact.get_department_display }}</td>
<td>{{ contact.room_number }}</td>
{% if contact.is_past_due == 'no_visit_performed' %}
<td class="info">{{ contact.last_visit }}<a href="{{ contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% elif contact.is_past_due == 'visit_good' %}
<td class="success">{{ contact.last_visit }}<a href="{{ contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% elif contact.is_past_due == 'visit_old' %}
<td class="warning">{{ contact.last_visit }}<a href="{{ contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% elif contact.is_past_due == 'need_visit' %}
<td class="danger">{{ contact.last_visit }}<a href="{{ contact.update_visit_date }}"> {% bootstrap_icon "plus-sign" %}</a></td>
{% endif %}
</tr>
{% empty %}

Is this something that is possible, the performing a CRUD from a template link? Or am I going about this the wrong way? Any help is greatly appreciated. Thank you very much!


/r/djangolearning
https://redd.it/6wd8ue
Is there any tutorial on how to run pyaudio with flask?

I'm basically trying to record audio through a clients web browser from a remote server. I was hoping to use this python script (which imports pyaudio) below to record.


import pyaudio
import wave

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "file.wav"

audio = pyaudio.PyAudio()

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True,
frames_per_buffer=CHUNK)
print ("recording...")
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print ("finished recording")


# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

However i am not sure what to do about the frontend. Is it a simple html form with a post request? I know that it wouldnt make any sense if that were solely the case. If anyone has gone through something similar as this, can you pinpoint me to some tutorials or documents available on how i can connect the python script to a web browser via flask?

Thanks

/r/flask
https://redd.it/6wg24z
Jupyter notebook code cell empty lines / scrolling

Since today, all my jupyter code cells have some empty lines at the end of a code block which are not real lines that I can delete, but rather is just empty space. In theory, this does not bother me, but unfortunately, each cell thus has scrolling available, and I inevitable scroll all the time in a cell which is quite annoying. It seems to only happen in Chrome though.

Anyone got an idea how to tackle this? Thanks.

/r/IPython
https://redd.it/6wjm2z
share your jwt/swagger implementation?

I'm having a hard time with this.

Here's what I have so far. The docs work, but the problem is it's not giving me the ability to enter a token on the "try me out!" examples. Also, when passing the token it's expecting `Authorization: JWT <token>` but per setup it's receiving `Authorization: <token>`. I don't want to remove the `JWT` prefix.

settings.py

...
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),

'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': None,
}

SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'jwt': {
'type': 'apiKey',
'description': 'jwt Token',
'name': 'Authorization',
'in': 'header'
}
},
'USE_SESSION_AUTH': False,
'SHOW_REQUEST_HEADERS': True,
'JSON_EDITOR': True,
}
...

urls.py

...
schema_view = get_schema_view(title='My API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/docs', schema_view, name='docs'),
url(r'^rest-api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/v1/auth/obtain/', obtain_jwt_token),
url(r'^api/v1/auth/refresh/', refresh_jwt_token),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
...


/r/django
https://redd.it/6wnsjs
Is there a way to make shell context in Django like in Flask?

What I mean is whenever I use python manage.py shell I don't want to keep typing the imports I need from my models, such as from models import User. In Flask, there is a way so that whenever you call python manage.py shell User is already a variable in the shell that you can reference without importing. Can you do a similar thing in Django?

/r/django
https://redd.it/6woap1
Has anyone had problems with Django settings files not interpreting environment variables correctly?

-----------------------
EDIT: Solved! Thanks /u/dirtybutter and /u/mipadi!
-----------------------


I feel like I've come across a sort of weird problem here. On my local machine, I work in virtualenvs when I am building things. Then I primarily push projects up to Heroku.

On most of my projects that are public-facing I set them up using env variables for sensitive stuff like DEBUG, SECRET_KEY, etc. Well a couple days ago I had an issue where I couldn't get debug to turn off on one of my projects on Heroku even though I had this line in my settings file:

DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))

On the Heroku side, just like I always do, I set an ENV variable with the cli like so:

heroku config:set DJANGO_DEBUG=" " #Empty string evals to false

So for whatever reason that wasn't working to turn off debug on Heroku, and it seemed like Heroku wasn't interpreting it correctly because when I would print the variable using the python shell, with that same code above (i.e. bool(...)) when running bash on the Heroku dyno it would still come back as true no matter what I set it as. Finally I adjusted the settings file in my project so now it says this:

if os.environ.get('DJANGO_DEBUG') == 'True':
dbg = True
else:
dbg = False

DEBUG = dbg #bool(os.environ.get('DJANGO_DEBUG', True))

That fixed the problem on Heroku. HOWEVER, now when I run the local python server on my local machine during development, all of a sudden I can't load my static files?!?! If I set an env variable locally on my machine called DJANGO_DEBUG and set it to 'True' (note it's a STRING not a boolean) the application still has debug off. If I change the settings file back to what it originally was, DEBUG = bool(os.environ.get('DJANGO_DEBUG', True)), then my static files load again and debug acts normally, but then debug won't be interpreted right on Heroku!

So basically, my question is: WTF!?!?!?! I don't know what changed...if it's a python versioning thing, a heroku thing, or a django version thing, or something totally different. I have at least 10 other projects running on Heroku AND locally right now and I have used this syntax for years so I don't know what the hell changed or why my settings file doesn't work right on my local machine when I use the "long form" if statement, but doesn't work right on Heroku when I use the short form.

Any ideas? Thanks!!

/r/django
https://redd.it/6wl4bq
Building this website using Flask. Feeback needed!

Hi,

I created [https://apileap.com](https://apileap.com) using Flask as the main framework and have to say that it has been an wonderful experience so far. There is a lot of nice extensions and I love being able to keep everything as simple as possible.

I do have a few questions though.

What deployment options do you recommend?
I currently use **nginx**, **gunicorn** and **gevent** on **EC2**. Do you think there are better options? How do you think I should scale if I ever need to? Anybody tried [Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/) with Flask?

What do you think about the website? What can I improve? Do you think it might be useful?

The website offers only one API right now but the idea is to offer several easy to use APIs for small companies in the near future. Do you think it might be interesting for your company? What API would you like to see added? I was thinking about currency conversion API, IP geolocation API, phone number validation API, sms API, ...

For the curious, here are the dependencies I use:

- Flask==0.12.2
- Flask-SQLAlchemy==2.2
- Flask-Security==3.0.0
- Flask-DebugToolbar==0.10.1
- Flask-Migrate==2.0.4
- Flask-Admin==1.5.0
- SQLAlchemy==1.1.11
- gunicorn==19.7.1
- psutil==5.2.2
- gevent==1.2.2
- requests==2.18.3
- stripe==1.62.0
- websocket-client==0.44.0
- Fabric3==1.13.1.post1

And for the front end:

- jquery==3.2.1
- bootstrap==4.0.0-beta
- vue=2.4.2

Have a good day!

Tim

/r/flask
https://redd.it/6wpynb
What's everyone working on this week?

Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.


/r/Python
https://redd.it/6wrgil
The Google Brain team will be back for its second AMA on September 13

Happy to announce the Google Brain team will be back in /r/MachineLearning for a second AMA on September 13. Hear how the team’s research and focuses have evolved in the past year, including updates on work in healthcare, creativity, human-AI interaction, and more.

A thread will be created before the official AMA time for those who won't be able to attend on that day.


/r/MachineLearning
https://redd.it/6wle45
I have created a collection of resources I used to learn python and Django! I'll post it here for everyone looking for a place to start!
https://mindweb.network/board/how-to-create-a-modern-website-with-django

/r/djangolearning
https://redd.it/6x0nob
Django Install Script for Ubuntu 16.04

Hey there, since I found this subreddit after already sharing this in the Django-subreddit, I wanna share my link to the original post here. :)

[Django Install on Ubuntu 16.04](https://www.reddit.com/r/django/comments/6wu4gu/django_install_i_am_just_a_newbie_and_i_did_this/?ref=share&ref_source=link)

Be free to comment here, or just use the real topic in /r/django as posted above.

/r/djangolearning
https://redd.it/6wxdxl