I am developing a custom usermodel for my application in django, by using AbstractUser.
But I am getting a UNIQUE constraint failed error while using add user + from django admin.
I have also tried to add unique = False in the EmailField
class User(AbstractUser):
id = models.BigAutoField(primary_key=True)
rollno = models.CharField(null=True,unique=True,max_length=15)
email = models.EmailField(blank=True,null=True,unique=False)
Error :
....
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: Accounts_user.email
[28/Jun/2022 05:54:58] "POST /admin/Accounts/user/add/ HTTP/1.1" 500 233697
The add form does not have a email field, submits a blank email.
(PS : I can add user by signup form of my application, change user of django admin is also working.)\
in the above code, there should not be any problem with migrations. i think your old migrations are creating problem here. check your old migrations and delete them.
Related
I was able to create a schema (and I confirmed this via database) but for some reason, I am getting a Can't create tenant outside the public schema. Current schema is error when creating schema and then also I am getting this error No tenant for hostname when I try to visit the tenants domain and I am not sure what is causing it. Below is my code:
views.py
def post(self, request):
form = CreatePortalForm(request.POST)
if form.is_valid():
getDomain = form.cleaned_data.get('name')
instance = form.save(commit=False)
user_id = request.user.id
user = User.objects.get(id=user_id)
tenant = Client(schema_name=getDomain, name=getDomain, created_by=user)
tenant.save()
domain = Domain()
domain.domain = getDomain + ".example.com:8000"
domain.tenant = tenant
domain.is_primary = True
domain.save()
with schema_context(tenant.schema_name):
instance.save()
redirect = 'http://' + getDomain + '.example.com:8000'
return HttpResponseRedirect(redirect)
return render(request, "registraton/create_portal.html", {"form": form})
For example, I have created three schemas:
tenant1
tenant2
tenant3
All three tenants have created the tables in the database, but I get the Can't create tenant outside the public schema. Current schema is error when running the above script to create the schema and domain or I get the No tenant for hostname when trying to visit the tenants domain.
Like I said, the schema is creating and migrating successfully but I still cannot get to the domain.example.com as it throws the No tenant for hostname error. Any ideas on what is causing this?
The django-tenants docs says that you shouldn't specify the port for your domain.
See this here
I have a Django server (Using PostGis) and I want to disable everything related to authentication:
When entering the admin no authentication will be required
In the admin hide the Users/Groups
After searching online I tried the combination of this & this
It does get me the result I hoped for, until I try to add an object via the admin. Then I get an IntegrityError:
insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id"
DETAIL: Key (user_id)=(1) is not present in table "auth_user".
I tried solving it using solutions like this and it didn't help.
I don't mind having a solution in a whole new approach as long as the end goal is acquired.
Thanks ahead,
As the Django project is running in dockers, and can be deployed when the users already exist or don't I ended up doing:
# Create superuser for admin use in case it doesn't exist
try:
User.objects.get_by_natural_key('admin')
except User.DoesNotExist:
User.objects.create_superuser('admin', 'admin#comapny.com', '123456')
Hope this helps someone one day. Full use:
from django.contrib import admin
from django.contrib.auth.models import User, Group
# We add this so no authentication is needed when entering the admin site
class AccessUser(object):
has_module_perms = has_perm = __getattr__ = lambda s,*a,**kw: True
admin.site.has_permission = lambda r: setattr(r, 'user', AccessUser()) or True
# We add this to remove the user/group admin in the admin site as there is no user authentication
admin.site.unregister(User)
admin.site.unregister(Group)
# Create superuser for admin use in case it doesn't exist
try:
User.objects.get_by_natural_key('admin')
except User.DoesNotExist:
User.objects.create_superuser('admin', 'admin#optibus.co', '123456')
I copied the full example code from: [customizing admin user][1] (part of the django documentation), but when I run it the django will not came out error,but when i add a user ,the django will the came out following error .
I have not changed any code for the example,and setting follow up the document.
follow up link is example:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example
Error:
IntegrityError at /admin/app01/myuser/add/
NOT NULL constraint failed: app01_myuser.last_login
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/app01/myuser/add/
Django Version: 1.8.5
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: app01_myuser.last_login
Exception Location: /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 318
There is clearly a discrepancy between the custom user model you are using from the Django sample code and the definition of the table it represents in database. The error is from the database saying the last_login column of the app01_myuser table has a NOT NULL constraint on it and you are trying to create a user with that field NULL.
Your MyUser model contains the last_login field inherited from AbstractBaseUser. Here is the definition of last_login from the AbstractBaseUser class:
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
Based on that definition of last_login, the NOT NULL constraint should not exist in your database.
Make sure your database is up to date by running migrations. Watch for any errors that occur when running the migrations.
You can also check the app01 migrations code to try to see when and why app01_myuser was created with the NOT NULL constraint in the first place.
I have a Django app that gets it's data completely from apis. so I don't have to use database. Session data is stored on signed cookies. I tried to code a custom User model and a custom auth backend like on the docs, but I get the following error:
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'my_app.MyUser' that has not been installed
My settings.py:
AUTH_USER_MODEL = 'my_app.MyUser'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',
'my_app.backends.LoginAuthBackend',)
models.py:
class MyUser(object):
def save(self):
pass
objects = None
username = ""
Here, If a try use the AbstractUser from django instead of Object I got the following error: AttributeError: 'NoneType' object has no attribute '_meta' or the db table doesn't exit.
backends.py
class LoginAuthBackend(object):
def authenticate(self, username=None, password=None):
if username and password:
try:
response = my_auth_function(username, password)
if response.status_code == 200:
token = response.get('my_key')
user = MyUser()
return user
except MyCustomException:
return None
It's drives me crazy. Looks like Django that's not easy to use without a DB.
EDIT
After several of tries, a simple way to solve this is remove 'django.contrib.auth.backends.ModelBackend' from AUTHENTICATION_BACKENDS and AUTH_USER_MODEL from settings. The model continues basically the same way. works smoothly
The default set of authentication back-end processors is defined in the AUTHENTICATION_BACKENDS setting. See the Django documentation for Customizing authentication.
By default, AUTHENTICATION_BACKENDS is set to:
['django.contrib.auth.backends.ModelBackend']
That’s the basic authentication backend that checks the Django users database and queries the built-in permissions.
So, if you don't want the django.contrib.auth.backends.ModelBackend authentication method, remove that from the list. You'll probably want to find (or create) a different one and add that to the list.
Last Month i posted question on stackoverflow and on Django-Users group on G+ and on django website too. But i didn't find any answer that can solve my problem. What i want to do is to add new permission named as view in django admin panel, so user can only view data!. I also followed different patches from django website and tried django-databrowse but nothing works as expected. I then finally decide to edit views of auth/admin. Now what i am going to do is to add view permission like:
1. Added 'view' to default permission list
#./contrib/auth/management/init.py
def _get_all_permissions(opts):
"Returns (codename, name) for all permissions in the given opts."
perms = []
for action in ('add', 'change', 'delete', 'view'):
perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw)))
return perms + list(opts.permissions)
2. Test the 'view' permission is added to all models
run manage.py syncdb
After this i can assign only view permission to user. Now this view permission must work too. So i am writing this code: in view.py of django-admin
for per in request.user.user_permissions_all():
print per
This code prints permissions assigned to login user like auth | permission | can view department etc
Now i can get permission type and model name by splitting this sentence. I will get all the model name of application and will match that which data must b visible. This is again not what i really need but can work.
So my question is :
* Is this is what i should do or is there any other way too. I just want a solution that must works as expected. Need Your Assistance *
Adding 'view' permission to default permissions list
Your solution works, but you should really avoid editing source code if possible. There's a few ways to accomplish this within the framework:
1. Add the permission during post_syncdb():
In a file under your_app/management/
from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
def add_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
# for each of our content types
for content_type in ContentType.objects.all():
# build our permission slug
codename = "view_%s" % content_type.model
# if it doesn't exist..
if not Permission.objects.filter(content_type=content_type, codename=codename):
# add it
Permission.objects.create(content_type=content_type,
codename=codename,
name="Can view %s" % content_type.name)
print "Added view permission for %s" % content_type.name
# check for all our view permissions after a syncdb
post_syncdb.connect(add_view_permissions)
Whenever you issue a 'syncdb' command, all content types can be
checked to see if they have a 'view' permission, and if not, create
one.
SOURCE: The Nyaruka Blog
2. Add the permission to the Meta permissions option:
Under every model you would add something like this to its Meta options:
class Pizza(models.Model):
cheesiness = models.IntegerField()
class Meta:
permissions = (
('view_pizza', 'Can view pizza'),
)
This will accomplish the same as 1 except you have to manually add it to each class.
3. NEW in Django 1.7, Add the permission to the Meta default_permissions option:
In Django 1.7 they added the default_permissions Meta option. Under every model you would add 'view' to the default_permissions option:
class Pizza(models.Model):
cheesiness = models.IntegerField()
class Meta:
default_permissions = ('add', 'change', 'delete', 'view')
Test the 'view' permission is added to all models
As for testing the whether a user has the permission, you can test on the has_perm() function. For example:
user.has_perm('appname.view_pizza') # returns True if user 'Can view pizza'