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
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
from many duplications to 0: optimize my queryset

I dunno how good this queryset is but according to django_toolbar my queryset had many duplications that made me feel dumb but with reading more carefully the documentation
https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-related
especially prefetch_related
this made me make a robust queryset with 0 duplications
my queryset
https://imgur.com/hgjHPOW
my post model
https://imgur.com/Q0H7M25
my comment model
https://imgur.com/O1c7AS2
django_toolbar
https://imgur.com/O1c7AS2
is there a clear way to optimize it without all this hassle plz don't forget put it in comment

/r/django
https://redd.it/8sdphl
[AF] How should I go about unit testing my flask RESTplus API?

Can I use pytest? What else do I need?

/r/flask
https://redd.it/8s4mln
Is there a way to access a Flask Session variable outside of the context of a request?

I know session variables can only be accessed once there is a client -> server request but I have a thread that runs concurrently outside of a request. I tried the "with app context" conditional that didn't quite work.
Any ideas?

/r/flask
https://redd.it/8rytzd
Need advice and recommendations to build a Blog Engine

Hi,

I'm to build a blog engine/CMS. Features I want to implement:

1. API based (totally)
2. reusable (can be easily embedded in larger projects)
3. database agnostic (SQL basically and PostgreSQL preferably)
4. internal good (but not complex) search engine
5. supports different post types (I want to know how to generalise the following post types)
1. gallery item (image with title and description)
2. blog post (ordinary post that might use images and videos inside)
3. project post (project title, description, url, image, embedded demo(like iframe)))
4. about us/contact us post (like pages)
6. with tags only (without categories --first tag should be the main category or so--)
7. media centre to upload images and files
8. resources (posts/images/files) should be also accessible via ID or Slugs
9. should I implement user roles and authentication? how?
10. What about testing? library to use, framework or just the standard
11. And Documentations?
12. Please feel free to add Your suggestions and how to implement it.

I've finished Miguel's tutorials and I want to do something big to apply what I learned and learn more. I want some insights on what I should and what I shouldn't do, libraries to use, things to consider, recommended methods, what to do first and what to do later? etc.

Mostly, I will use Vuejs to build the front-end, but I want to build the blog first because I want to embed it in a larger website. And I need it to be standalone so that I can share it.

Thanks in advance :)

/r/flask
https://redd.it/8si0pf
Django Class-Based/Generic Views - An Introduction

When starting out, you most likely used **function-based views**.

**Class-Based views** are an alternative to them. As the name suggests, you group your code into methods that

live inside of a class.

If you have a hard time understanding what they are or why they are used, keep reading ;)

This function-based view:

def book_list(self):

# Note: you can handle different request methods by checking for the appropriate
# value of request.METHOD with if/else statements
# e.g. 'GET', 'POST', ...

book_list = Book.objects.all()
return render(request, 'index.html', {'book_list': book_list})

Could roughly be written as this class-based view:

class BookListView(View):

# Note: you can handle different request methods using the appropriate function names
# e.g. get(), post(), ...

def get(self, request):
book_list = Book.objects.all()
return render(request, 'index.html', {'book_list': book_list})

Well, we didn't gain much, right?

But how about splitting our code into more meaningful functions that live inside of the same class?

class BookListView(View):

def get(self, request):
return render(request, 'index.html', {'book_list': self.get_queryset()})

def get_queryset(self):
return Book.objects.all()

Well, I now have two functions instead of one. So what?

1. **Separation of concerns** is easier this way.
2. This allows us to use **subclass** from another class and easily override some methods, while **inheriting** the other methods, which still will do their thing. Turns out, that django implements certain generic views for us, which take care of implementing the business logic of common web development tasks for us.

Let's get back to our example and rewrite it subclassing from a generic view:

class BookListView(ListView):
model = Book
template_name = 'index.html'

Well, that was short. Still, we will get the same result. There are many other generic views you can use, such as the **DetailView** for object detail pages or **FormView**, which makes form handling easy.

Of course, you can override context data as well by simply overriding certain functions on the listview.

If you want more information on that, check out my 6 minute video on the subject:

[**https://youtu.be/oA60bl\_HFIk**](https://youtu.be/oA60bl_HFIk)

Take care!

*(Note: code above is untested and doesn't include import statements. If you spot any errors, make sure to let me know.)*

/r/djangolearning
https://redd.it/8sja4x
relation "django_content_type" does not exist despite "manage.py migrate contenttypes" being run

Hello everyone,

when i run ```python -Wall manage.py test;``` to see what i'll need to see what i'll have to pay attention when updating to a newer django version i get the following error:

```django.db.utils.ProgrammingError: relation "django_content_type" does not exist```

according to the internet i should run ```python manage.py migrate contenttypes```

however when i do so it shows the following error:

```django.db.utils.ProgrammingError: relation "auth_permission" does not exist```

so i run:

```python manage.py migrate auth;``` which results in:

```django.db.utils.ProgrammingError: relation "django_site" does not exist```

which is solve by running:

```python manage.py migrate sites;```

but when i rerun ```python -Wall manage.py test;``` i get the same error again.

The only reason i'm including the migrations of auth and sites in here is because the three seem to have a cyclical dependency, auth depends on sites, contentypes depends on auth and sites depends on contentypes (going by the errors they print depending on which migration i try to run first).

The three of them are included in the installed apps as:

'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',


Does anyone know what is causing this and how i can fix this?

/r/djangolearning
https://redd.it/8shzg5
Sentdex on Udemy's awful business practices

https://youtu.be/X7jf70dNrUo

Very interesting perspective

/r/Python
https://redd.it/8sl76u
Is Python getting slower?

[https://github.com/reinderien/py-cat-times](https://github.com/reinderien/py-cat-times)

In particular - for certain concatenation operations that I've profiled in the link above, why does it appear that some operations (e.g. `str join`) are getting slightly slower (in the 10s of &#37;) while others (e.g. successive `+` on a "bytes") have gone from O(n) to O(n²)?

[One of the graphs from R, showing performance differences over Python versions](https://i.redd.it/h47304o4s6511.png)

[One of the graphs from R, showing some concatenation methods that are O\(n²\)](https://i.redd.it/fp9y8gihs6511.png)

Is it that `pyenv` is doing a poor job in compiling Python on my MacBook, or that my profiling technique has problems, or is this real?

/r/Python
https://redd.it/8sjybt