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 next after basic CRUD?

Hello guys,

It's me again with another dumb question.

I've "finished" few basic apps in my project. I have working CRUD for each app/model and I feel lost now. I'd like to add few things, but I'm not sure what's the best next step

\- Dashboard with charts, maybe few basic forms to add quickly object for specific model

\- Few simple "buttons" to do special actions eg. quickly increase/decrease amount in IntegerField

\- Ability to use custom script (It takes list of IDs and create pdfs of chosen ids), smth like form in which i could add ids and amounts of each id to pass it to the script

What should I do? Things like this require some frontend tools like react? Or can I do it with plain Django?

If I have to use frontend framework, which is better (for project and future job), react or vue?

If I use frontend framework, do I need to create REST API for each app in my project?

Thanks for any advices!

/r/djangolearning
https://redd.it/8s276j
Python is now the most frequent weekly tag on StackOverFlow

/r/Python
https://redd.it/8s2uaf
Overiq Djangobin - A project based tutorial for Django 1.11

Hello everyone!

I have just finished writing Django 1.11 tutorial, where we will build a pastebin application called djangobin.

Tutorial link: https://overiq.com/django/1.11/intro-to-django/

Live Demo: http://overiq.pythonanywhere.com/

Github source: https://github.com/overiq/djangobin


/r/django
https://redd.it/8rz0h4
i have prebinned data. how can i use pandas and seaborn to display histograms based on those bins

see title.

I have csv files of this form

mass (g),count

0-499,600

500-999,2244

1000-1499,3245

...

4500-4999,2095

5000-8165,201



i have 6 such csv files and i'd like to see 6 histograms. the fact that the data is prebinned is giving me issues. i'd appreciate a hint! thanks for your time.

/r/pystats
https://redd.it/8s5tty
MozartFlow: Doing analysis on audio like gender classification, instrument recognition, voice separation, genre classification | Not completed; If anyone interested, do collab.
https://github.com/techcentaur/MozartFlow

/r/Python
https://redd.it/8s6ll7
Need help with chart.js and django.

Im using chart.js to display charts in my django website. I am also using an API call that then parses out JSON data for the chart using python. Does anyone then know how to use an axios call within javascript to call and display the data through my index.html file?

/r/django
https://redd.it/8s89tb
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/8s95kt
queryset appears empty in debugger during testing, but not in console

Hello,

I'm testing REST APIs with `rest_framework.test.APITestCase`, using their client for making requests and `model_mommy` for creating objects in the `setUp()` method.

The general working is quite simple: the view is supposed to fetch a User and an object, and assign permissions for the former to the latter by means of django-guardian's `assign_perm`; the test creates a user and a group in the `setUp` method, then the actual test performs a POST passing their pk's as payload.

The issue I'm seeing, is that when the `User.objects.filter(pk__in=people_ids)` instruction is executed, the value I see in the debugger is that of an empty queryset, while if I type the exact same line in a console connected to the same session as the debugger I see the actual value being found.
Then the view gets to the `assign_perm` instruction, and it crashes with an `IndexError: list index out of range` error on the first evaluation of the queryset itself, which happens on the for loop at line 247 in the file core.py of the django-guardian library.

Is there something obvious that I should be looking at, because I really cannot wrap my head around this.

(django 1.11.13)

Thanks

/r/django
https://redd.it/8s9y48
Made a custom user, then tried to createsuperuser but got TypeError: hasattr(): attribute name must be string

I've created a new Django project and the first thing I did was create a custom user with the help of Django docs: https://docs.djangoproject.com/en/2.0/topics/auth/customizing/

After I wrote all the code for a custom user, and after I did **makemigrations** and **migrate** for the first time in this Django project, I tried to create a superuser while my virtual env is active by writing:

python manage.py createsuperuser

But it gave me this error:

> TypeError: hasattr(): attribute name must be string



I wrote all the custom user code in an app called **accounts**.


In the **settings** file I added 'accounts' to the INSTALLED_APPS list, and added in the bottom this line:

AUTH_USER_MODEL = 'accounts.CustomUser'

Here's all my source code, starting with models.py:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin


class CustomUserManager(BaseUserManager):

def create_user(self, email, password=None):

if not email:
raise ValueError("Users must have an email address")
if not password:
raise ValueError("Users must have a password")

user = self.model(
email = self.normalize_email(email)
)

user.set_password(password)
user.save(using=self._db)

return user


def create_staffuser(self, email, password, first_name, last_name):

if not first_name:
raise ValueError("Staff and superusers must have a first name")
if not last_name:
raise ValueError("Staff and superusers must have a last name")

user = self.create_user(
email,
password=password
)

user.first_name = first_name
user.last_name = last_name
user.is_staff = True
user.save(using=self._db)

return user


def create_superuser(self, email, password, first_name, last_name):

user = self.create_staffuser(
email,
password=password,
first_name=first_name,
last_name=last_name
)

user.is_admin = True
user.is_superuser = True # Not sure if this is needed
user.save(using=self._db)

return user


class CustomUser(AbstractBaseUser, PermissionsMixin):

email = models.EmailField(null=True, max_length=80, unique=True)
USERNAME_FIELD = 'email'
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=25, blank=True, null=True)
last_name = models.CharField(max_length=25, blank=True, null=True)
date_joined = models.DateField(auto_now_add=True, null=True)
REQUIRED_FIELDS = [first_name, last_name]

objects = CustomUserManager()

def __str__(self):
return self.email

def get_short_name():
return first_name

def get_full_name():
return first_name + ' ' + last_name

Then I wrote this in forms.py:

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import CustomUser


class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

class Meta:
model = CustomUser
fields = ('email', 'first_name', 'last_name')

def clean_password2(self
):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2

def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user


class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()

class Meta:
model = CustomUser
fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin')

def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]

And in admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import CustomUser
from .forms import UserCreationForm, UserChangeForm


class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm

# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name',)}),
('Meta', {'fields': ('date_joined', 'last_login', 'is_active',)}),
('Permissions', {'fields': ('is_admin', 'is_staff',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name' 'password1', 'password2')}
),
)
search_fields = ('email', 'first_name')
ordering = ('email',)
filter_horizontal = ()

admin.site.register(CustomUser, UserAdmin)


This is the entire error traceback:

Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 282, in run_from_argv
options = parser.parse_args(argv[2:])
File "/home/impressive_response/Projects/project-root/project_env/lib/python3.6/site-packages/django/core/management/base.py", line 54, in parse_args
return super().parse_args(args, namespace)
File "/usr/lib/python3.6/argparse.py", line 1739, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/lib/python3.6/argparse.py", line 1760, in parse_known_args
if not hasattr(namespace, action.dest):
TypeError: hasattr(): attribute name must
SQLAlchemy - How does the relationship() function work?

I've ripped this straight out of the mega tutorial:

class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')

def __repr__(self):
return '<User {}>'.format(self.username)

class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))


I looked at the SQLAlchemy documentation and I'm still having trouble deciphering this. When I run my shell and create a post authored by my first list in my user query, my post object correctly has a user_id of the user who authors that post. But How does it know this? Does the `ForeignKey` argument look at all my classes and and find the `id` field under user? If so, that much makes sense. But how exactly creating a relationship in the User class, and then Post class knowing to relate it's foreign key to the author of the Post is an enigma to me. Anyone care to explain please.

/r/flask
https://redd.it/8s2fmq
Best open source Flask repos for learning design patterns?

I'm a remote dev and am trying to enhance my code organization. Anybody have any good flask repositories that will help teach organization and design patterns?
I'd like to concentrate on large Blueprint-organized RESTful apps, but mine often get out of hand.

/r/flask
https://redd.it/8segyj