Django-AttributeError ‘User’ object has no attribute ‘backend’ (But….it does?)

You must call authenticate before you can call login. authenticate sets an attribute on the object noting which backend has successfully validated it and clearing it for login, which isn’t happening in your code (and that’s the attribute that is missing). Documentation: https://docs.djangoproject.com/en/1.8/topics/auth/default/#how-to-log-a-user-in — check out the little callout that says “calling authenticate() first”.

Django: Populate user ID when saving a model

UPDATE 2020-01-02 ⚠ The following answer was never updated to the latest Python and Django versions. Since writing this a few years ago packages have been released to solve this problem. Nowadays I highly recommend using django-crum which implements the same technique but has tests and is updated regularly: https://pypi.org/project/django-crum/ The least obstrusive way is … Read more

Can django’s auth_user.username be varchar(75)? How could that be done?

There’s a way to achieve that without touching the core model, and without inheritance, but it’s definitely hackish and I would use it with extra care. If you look at Django’s doc on signals, you’ll see there’s one called class_prepared, which is basically sent once any actual model class has been created by the metaclass. … Read more

Get user information in django templates

An alternate method for current Django versions: {% if user.is_authenticated %} <p>Welcome, {{ user.get_username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} Note: Use request.user.get_username() in views & user.get_username in templates. Preferred over referring username attribute directly. Source This template context variable is available if a … Read more

Using Django auth UserAdmin for a custom user model

After digging around the Django source code for a while, I found a working soultion. I am not totally happy with this solution, but it seems to work. Feel free to suggest better solutions! Django uses UserAdmin to render the nice admin look for User model. By just using this in our admin.py-file, we can … Read more

Check permission inside a template in Django

If you are looking to check for permissions in templates, the following code would suffice: {% if perms.app_label.can_do_something %} <form here> {% endif %} Where model refers to the model that the user need permissions to see the form for. Refer to https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions for more examples. The currently logged-in user’s permissions are stored in the … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)