zsoldosp / django-currentuser Goto Github PK
View Code? Open in Web Editor NEWConveniently store reference to request user on thread/db level.
License: BSD 3-Clause "New" or "Revised" License
Conveniently store reference to request user on thread/db level.
License: BSD 3-Clause "New" or "Revised" License
I have the following model:
class Business(models.Model):
...
created_on = models.DateTimeField(auto_now_add=True, editable=False)
created_by = CurrentUserField(null=True, blank=True, editable=False, # Attention 4
on_delete=models.SET_NULL)
And I am testing this in the following test case:
class Base(TestCase):
def setUp(self):
self.padmin = User.objects.create_user('padmin')
for u in (self.padmin,):
u.set_password('password')
u.save()
self.business = Business.objects.create(name='name', address='address',
phone_number='123-456-7890')
self.business2 = Business.objects.create(name='name2', address='address',
phone_number='123-456-7891')
def STEP_create_instance(self):
self.client.login(username='padmin', password='password')
url = '/'
self.client.post(url, {}) # Attention: 1
class SafesiteProductionFlowIntegrationTest(Base):
def test_one(self):
self.STEP_create_instance() # Attention: 2
def test_two(self):
self.STEP_create_instance() # Attention: 3
When I run this test, I am getting the following error:
System check identified no issues (0 silenced).
..E
======================================================================
ERROR: test_before_split2 (instances.tests.test_viewflow.SafesiteProductionFlowIntegrationTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
psycopg2.IntegrityError: insert or update on table "businesses_business" violates foreign key constraint "businesses_business_created_by_id_25175862_fk_auth_user_id"
DETAIL: Key (created_by_id)=(1) is not present in table "auth_user".
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/test/testcases.py", line 209, in __call__
self._post_teardown()
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/test/testcases.py", line 893, in _post_teardown
self._fixture_teardown()
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/test/testcases.py", line 1041, in _fixture_teardown
connections[db_name].check_constraints()
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 235, in check_constraints
self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
django.db.utils.IntegrityError: insert or update on table "businesses_business" violates foreign key constraint "businesses_business_created_by_id_25175862_fk_auth_user_id"
DETAIL: Key (created_by_id)=(1) is not present in table "auth_user".
----------------------------------------------------------------------
Ran 2 tests in 0.438s
FAILED (errors=1)
Commenting out the following removes the error:
Attention: 4
Attention: 1
Attention 2
and Attention 3
) methods making this test test a single methodIt seems like CurrentUserField is causing some issues during tearDown.
Any ideas?
ERROR: Cannot install -r requirements.txt, Django==4.0 and django-currentuser==0.5.3 because these package versions have conflicting dependencies.
The conflict is caused by:
django-currentuser 0.5.3 depends on Django<3.3 and >=1.11.17; python_version >= "2.7"
Is this just a matter of adjusting the dependency requirement or are there any changes needed in the package?
In my tests, I create an object that has an CurrentUserField
. Up until recently everything worked, but now it fails with an SQLdb.IntegrityError
after upgrading to python 3.9
, django 3.2
and django-currentuser 0.5.3
.
I was able to resolve this by explicitly overriding the user in the setUp()
method of my test class as follows: _set_current_user(my_user)
. Is that the recommended approach? If so, we should document it somewhere.
Stacktrace:
ERROR: test_donation_bill (app.fairgeben.tests.test_donation.DonationInternalsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/opt/venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/opt/venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/opt/venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 312, in _query
db.query(q)
File "/opt/venv/lib/python3.9/site-packages/MySQLdb/connections.py", line 224, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`test_edonapi`.`fairgeben_donationcomment`, CONSTRAINT `fairgeben_donationco_created_by_id_5e9223c0_fk_users_use` FOREIGN KEY (`created_by_id`) REFERENCES `users_user` (`id`))')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/app/fairgeben/tests/test_donation.py", line 290, in test_donation_bill
self.assertRaises(
File "/usr/local/lib/python3.9/unittest/case.py", line 733, in assertRaises
return context.handle('assertRaises', args, kwargs)
File "/usr/local/lib/python3.9/unittest/case.py", line 201, in handle
callable_obj(*args, **kwargs)
File "/usr/src/app/fairgeben/models.py", line 631, in add_to_accounting
self._log_invalid_status_change(
File "/usr/src/app/fairgeben/models.py", line 553, in _log_invalid_status_change
DonationComment.objects.create(
File "/opt/venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/opt/venv/lib/python3.9/site-packages/django/db/models/query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
File "/opt/venv/lib/python3.9/site-packages/django/db/models/base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "/opt/venv/lib/python3.9/site-packages/django/db/models/base.py", line 763, in save_base
updated = self._save_table(
File "/opt/venv/lib/python3.9/site-packages/django/db/models/base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/opt/venv/lib/python3.9/site-packages/django/db/models/base.py", line 906, in _do_insert
return manager._insert(
File "/opt/venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/opt/venv/lib/python3.9/site-packages/django/db/models/query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/opt/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1416, in execute_sql
cursor.execute(sql, params)
File "/opt/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/opt/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/opt/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/opt/venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/opt/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/opt/venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/opt/venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/opt/venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 312, in _query
db.query(q)
File "/opt/venv/lib/python3.9/site-packages/MySQLdb/connections.py", line 224, in query
_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`test_edonapi`.`fairgeben_donationcomment`, CONSTRAINT `fairgeben_donationco_created_by_id_5e9223c0_fk_users_use` FOREIGN KEY (`created_by_id`) REFERENCES `users_user` (`id`))')
With django now supporting async, should we be trying to import asgiref.local.Local if available, which is a drop-in async replacement for threading.local?
Perhaps replacing:
from threading import local
With:
try:
from asgiref.local import Local as local
except ImportError:
from threading import local
Would be happy to make a PR for this, but not sure how to approach the situation where asgiref package is available vs when it is not.
Will you soon be supporting Django 5.1?
I have an abstract model
class BaseModel(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
added_by = CurrentUserField(blank=True, null=True, on_delete=models.SET_NULL, related_name='added_by')
modified_by = CurrentUserField(blank=True, null=True, on_delete=models.SET_NULL, related_name='modified_by')
class Meta:
abstract = True
and
class Company(BaseModel):
name = models.CharField(max_length=400)
nip = models.CharField(max_length=13, unique=True)
description = models.TextField()
year_established = models.CharField(max_length=4, blank=True, null=True)
www = models.URLField(blank=True, null=True)
logo = models.FileField(blank=True, null=True)
sectors = models.ManyToManyField(Sector, blank=True, null=True)
def __str__(self):
return f"{self.name}"
After adding Company through admin panel the added_by and modified_by field are blank.
Environment:
Problem:
When I run python manage.py makemigrations
I get the following warning. This warning is new after updating to the latest version of Django and django-currentuser. If I revert Django to 3.0.X
the warning will go away.
/home/admin/.local/share/virtualenvs/Project-HFzz1tdt/lib/python3.8/site-packages/django_currentuser/db/models/fields.py:57: UserWarning: You passed an argument to CurrentUserField that will be ignored. Avoid args and following kwargs: default, null, to.
warnings.warn(self.warning)
I have one reference to CurrentUserField
in my project:
from django.db import models
from django_currentuser.db.models import CurrentUserField
class UserTrackingModel(models.Model):
created_by = CurrentUserField()
class Meta:
abstract = True
I use UserTrackingModel
as a base class for some of my models, like so:
from camp.db_models import UserTrackingModel
class Foo(TimeStampedModel, UserTrackingModel):
name = models.CharField(default="", max_length=200, unique=True)
thing = models.ForeignKey(Thing, on_delete=models.PROTECT, null=False)
Desired Outcome
I would like to be able to generate migrations without getting a warning that could potentially turn into a bigger problem down the road.
I tested it with version 0.4.2 and it seems to work fine with django3.0 after editing parameters in setup.py.
Hi! I use this with django 3.2 and it works for me, although setup.py says it requires Django<3.2
Are there known problems with 3.2 or can you loose this restriction in a new release?
Thanks!
Add support for django 4.x - For now, the project is tagged to support django 3.2.x
Can we have an updated_by = CurrentUserField(on_update=True)
similar to auto_now=True
?
For our project we would like to save the username as string instead of having a foreign key.
Would it be possible to add this as a feature?
The following error appears when making migrations and migrating:
UserWarning: You passed an argument to CurrentUserField that will be ignored. Avoid args and following kwargs: default, null, to.
How can this be avoided?
I use Python 3.9 and Django 3.1.6
Currently the order in which this middleware is inserted in respect to AuthenticationMiddleware
and SessionMiddleware
does not matter as we use a closure that returns the request-scope only on-demand.
This closure can fail in certain setups (see #1 (comment)) and seems avoidable. Right now nothing speaks against requiring a fixed order where ThreadLocalUserMiddleware
is only allowed after the other two.
cannot update the django version 3.0 to 4.1
In my django project am not using the basic user table, I created custom user model,, when I used current user it gives me an error
townoftech_warehouse.Item.created_by: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
that is how I am using it in models.py
class Item(models.Model):
item_category = models.ForeignKey(Category, on_delete="PROTECT")
item_name = models.CharField(max_length=100, null=False)
item_quantity = models.IntegerField(default=1)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
created_by = CurrentUserField(settings.AUTH_USER_MODEL)
It seems there's an issue with the pinning of version.
It's currently impossible to use django-currentuser 0.4.1
with Django 2.2.1.
ERROR: django-currentuser 0.4.1 has requirement Django<2.0,>=1.11.17, but you'll have django 2.1.8 which is incompatible.
ERROR: django-currentuser 0.4.1 has requirement Django<2.3,>=2.2.1; python_version > "3.4", but you'll have django 2.1.8 which is incompatible.
Step to reproduce:
pip install django
pip install django-currentuser
On July 28, a new message was added to the readme file:
WARNING:
This project is currently frozen and will not longer be maintained. If there is someone interested in continuing to maintain this project please contact: [email protected] .
Does anyone feel called to do this?
I am trying to get the current user in settings.py but i am getting None.
According to github's REAEME.md
On Custom User Model
created_by = CurrentUserField()
updated_by = CurrentUserField(on_update=True)
it gives me this error
$ py manage.py makemigrations
SystemCheckError: System check identified some issues:
ERRORS:
authentication.User.created_by: (fields.E304) Reverse accessor for 'authentication.User.created_by' clashes with reverse accessor for 'authentication.User.updated_by'.
HINT: Add or change a related_name argument to the definition for 'authentication.User.created_by' or 'authentication.User.updated_by'.
authentication.User.updated_by: (fields.E304) Reverse accessor for 'authentication.User.updated_by' clashes with reverse accessor for 'authentication.User.created_by'.
HINT: Add or change a related_name argument to the definition for 'authentication.User.updated_by' or 'authentication.User.created_by'.
Then I Try to Solve like the following
created_by = CurrentUserField(related_name="+")
updated_by = CurrentUserField(on_update=True, related_name="+")
Then it gives me following warning
$ py manage.py makemigrations
E:\django\venv\lib\site-packages\django_currentuser\db\models\fields.py:57: UserWarning: You passed
an argument to CurrentUserField that will be ignored. Avoid args and following kwargs: default, null, to.
warnings.warn(self.warning)
Migrations for 'authentication':
authentication\migrations\0001_initial.py
- Create model User
- Create model Permission
- Create model Role
- Add field role to user
- Add field updated_by to user
Please help me to fix this warning and errors
It could be better NOT to specify the python and Django versions, just as a super low bar - i.e.: python 2.7 and Django 1.11, and simply list in the README (tox) which versions are supported
Would simplify life quite a bit as setuptools is never trivial :)
Django 2.0 has been released but this package currently requires 'Django>=1.8,<1.12' as dependency.
Hi,
would it be possible to add additional user object data?
I'm looking for users is_staff
or is_superuser
Need to work with this data in a place where I'm not able to get to the User object model.
And this plugin was already able to provide me with the username.
Thanks,
Christian
Talking about the support for Django 2.2, is there anything related on the roadmapping?
Getting this error on migration:
UserWarning: You passed an argument to CurrentUserField that will be ignored. Avoid args and following kwargs: default, null, to.
warnings.warn(self.warning)
Will Django 1.11.1 and 2.0.1 be supported by the pip package any time soon?
For my purposes I'd rather have null=False and it errors out if the value is None. Wondering the thought process on enforcing null=True?
IMO the CurrentUserField should not have on_delete=CASCADE
as a default parameter. Instead it should align with Django (3.2) ForeignKey field implementation, where the parameter for on_delete
is required.
The current behaviour might lead to unwanted deletion if the user is deleted.
Thank you for considering my request.
New to using this project, thanks for creating and maintaining it!
While creating tests for myself, I find myself wanting to set the current user. I've finally had success using the internal _set_current_user()
method. It would be great if there were an external facing testing toolset to make this easier/more accessible. Happy to make a go at it, if there's interest.
Just an update on when will the next release roll-out on Pypi? I still have to import directly from git, the latest commit fixes my problem now.
Thank you!
Django 2.1.4 has been released but this package currently requires 'Django<2.1,>=1.11' as dependency. Seems compatible though, just mentioning, tx.
When will v0.3 be published to pypi?
I am trying to get the current loggedin user in middleware[Database router middleware] but unable to get.
it is always gives me like below -
<function get_current_authenticated_user at 0x7fcb67062280>
please help me to get the loggedin user in my database router so i can manage all the databases from single middleware.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.