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
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/8mzdqf
What is the point of: EMAIL_HOST = 'localhost'

That is the default setting, and I wonder what it does.


I have a contact form on my website and I would like to use send email to my custom domain on protonmail which is the same domain that my website is using. I've added the records to my DNS like MX, SPF, etc so protonmail can use.


So, since my DNS is configured to be used by protonmail, I thought that having the default setting to EMAIL_HOST which is 'localhost' would mean it looks my DNS settings and sees it should use protonmail to send email. Is that how it works? Because I am really confused about all this.


How are you supposed to use 'localhost' exactly?

/r/djangolearning
https://redd.it/8n012a
Tutorial notebooks for demonstrating Jupyter capabilities?

My group at work has set up a JupyterHub instance for researchers in our office to use. There's a meeting tomorrow where my boss has asked me to talk to some of the other managers about what Jupyter is and why it's needed. Are there any good notebooks out there that can demonstrate some of the features of JupyterHub and Jupyter notebooks in ways that are easy for potentially non-technical people to understand?

/r/IPython
https://redd.it/8n09dy
Need HELP with building Recommender systems (using python)

Hello there! I am new to this amazing world of Machine Learning and have just completed Andrew NG's course in it. I want to get my hands dirty and build a Movies Recommender Systems from scratch. I searched a lot and most of the websites I landed on gave results using libraries in python which made the task extremely easy. My question is can we build such a system without using any library? (I mean not using libraries like sci-kit learn, surprise, numpy etc. )

Please help me out here.

/r/pystats
https://redd.it/8mzncv
CreateView and inlineformset_factory use with junction table

I'm trying to expand the use of the official django tutorial which builds a voting app. At the moment what I'm trying to do is to allow a user to create a poll, input the poll name, the poll options and invite the users he wants by email from the already registered users. In order to do that I have created a junction table called `EligibleVoters` with foreign keys to the `Poll` table and the `auth_user` table

my `model.py`:

class Poll(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', auto_now_add=True)
is_active = models.BooleanField(default=True)
activation_date = models.DateTimeField('Activation Date', blank=True, null=True)
expiration_date = models.DateTimeField('Expiration Date', blank=True, null=True)
public_key = models.CharField(max_length=30, blank=True)
hash = models.CharField(max_length=128, blank=True)
timestamp = models.DateTimeField(auto_now=True)

def __str__(self):
return self.question_text

def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'


class Choice(models.Model):
question = models.ForeignKey(Poll, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self):
return self.choice_text


class EligibleVoters(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
email = models.EmailField(null=True)

my `forms.py`:

from django.forms import ModelForm, inlineformset_factory
from django import forms
from .models import Poll, Choice, EligibleVoters, PollKeyPart, User
class PollForm(ModelForm):
activation_date = forms.DateTimeField(required=False)
expiration_date = forms.DateTimeField(required=False)
class Meta:
model = Poll
fields = ['question_text', 'is_active', 'activation_date', 'expiration_date']
class ChoiceForm(ModelForm):
class Meta:
model = Choice
exclude = ()
ChoiceFormSet = inlineformset_factory(Poll, Choice, form=ChoiceForm, extra=1)
class EligibleVotersForm(ModelForm):
class Meta:
model = EligibleVoters
fields = ['email']
EligibleVotersFormSetPoll = inlineformset_factory(Poll, EligibleVoters, form=EligibleVotersForm, extra=1)
EligibleVotersFormSetUser = inlineformset_factory(User, EligibleVoters, form=EligibleVotersForm, extra=1)

my `views.py`:

class NewPoll(CreateView):
model = Poll
fields = ['question_text', 'is_active', 'activation_date', 'expiration_date']
success_url = reverse_lazy('voting:index')

def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data['choices'] = ChoiceFormSet(self.request.POST)
data['eligible_voters_poll'] = EligibleVotersFormSetPoll(self.request.POST)
data['eligible_voters_user'] = EligibleVotersFormSetUser(self.request.POST)
else:
data['choices'] = ChoiceFormSet()
data['eligible_voters_poll'] = EligibleVotersFormSetPoll()
data['eligible_voters_user'] = EligibleVotersFormSetUser()
return data

def form_valid(self, form):
context = self.get_context_data()
choices = context['choices']
eligible_voters_poll = context['eligible_voters_poll']
eligible_vot
ers_user = context['eligible_voters_user']
with transaction.atomic():
self.object = form.save()
if choices.is_valid():
choices.instance = self.object
choices.save()
if eligible_voters_poll.is_valid() and eligible_voters_user.is_valid():
eligible_voters_poll.instance = self.object
eligible_voters_poll.save()
eligible_voters_user.instance = self.object
eligible_voters_user.save()
return super().form_valid(form)

And my html file:

{% extends 'base.html' %}
{% block content %}
{% load static %}
<h2>Poll Creation</h2>
<div class="col-md-4">
<form action='' method="post">
{% csrf_token %}
{{ form.as_p }}
<table class="table">
{{ choices.management_form }}
{% for form in choices.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row1">
{% for field in form.visible_fields %}
<td>
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<table class="table">
{{ eligible_voters_poll.management_form }}
{% for form in eligible_voters_poll.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row2">
{% for field in form.visible_fields %}
<td>
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Save"/> <a href="{% url 'voting:index' %}">back to the list</a>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="{% static 'voting/js/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row1').formset({
addText: 'add poll choice',
deleteText: 'remove',
prefix: 'Choice_set'
});
$('.formset_row2').formset({
addText: 'add eligible voter',
deleteText: 'remove',
prefix: 'EligibleVoters_set'
});
</script>
{% endblock %}

If I don't include the `EligibleVotersFormSetUser` the code works but the `user_id` in the `EligibleVoters` table remains null. If I include the `EligibleVotersFormSetUser` the
code gives me a `"EligibleVoters.user" must be a "User" instance.`
error. Somehow I need to associate each entry with the corresponding user\_id. What is the best way to do that?I got to where I am now by following [this tutorial](https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d). Also I would like to add validation to the email field of the form in order for the user to be able to invite only registered users.

/r/django
https://redd.it/8n18li
Server side caching using django cache framework

I am trying to cache my API response for a particular url using django cache framework and storing the cache in database. I am trying to cache the response for all the users who visit the particular page. I want it to be client independent. I have written a middleware to remove cookie from the request header because django cache uses url \+ cookie \+ other details to create cache key.

The cache is working on the user basis i.e. when a user hits the url it caches the response for that particular user only.

How can I use the same cache for all the users?

P.S: I have already set no\-cache for the client.

/r/django
https://redd.it/8my935
Calling an api from a different blueprint

I currently have two blueprints. I was wondering if there was a simple way to call an api from the second blueprint in the first blueprint aside from just explicitly calling it (if that's the answer, that's great too... I just want to make sure I am doing things the *correct* way).

bp1.py

@bp.route('/foo', methods=('GET',))
def foo():
do_something()
post_to_bar()

bp2.py

@bp.route('/bar', methods=('GET', 'POST'))
def bar():
if request.method() == 'POST':
do_something_else()

/r/flask
https://redd.it/8n2epo
Using custom model managers

I have been learning Django for over 1 year now, although most of my time is spent with html and css.

I am using Django 1.11.

I have read about custom model managers before but I considered them a little advanced for that time.

Recently, I have started reading about them.
In my current case I think that they would help me with filtering.

So, what's your use case for custom model managers ?
Do they make the code cleaner and/or improve performance ?

/r/django
https://redd.it/8n4txc
This media is not supported in your browser
VIEW IN TELEGRAM
[P] Realtime multihand pose estimation demo

/r/MachineLearning
https://redd.it/8n04hp
Question about jwt

I just started using `djangorestframework-jwt` and I have a few questions about it. Does a jwt get automatically created on signup/login? \(Do I need to otherwise?\). Or do my users have to manually input their credentials on a specific url to get theirs created?

/r/django
https://redd.it/8n7qsd