Django REST EmailAddress matching query does not exist - django

I am using django rest-auth and allauth to authenticate users. After successful signup and email verification, I implemented a login view which subclasses rest-auth.views.LoginView like below:
class ThLoginView(LoginView):
def get(self, request):
form = CustomUserLoginForm()
return render(request, "users/login.html", context={"form": form})
with my own form:
class CustomUserLoginForm(AuthenticationForm):
class Meta:
model = CustomUser
fields = ('email',)
The problem is that when I login I get this error:
DoesNotExist at /users/login/
EmailAddress matching query does not exist.
Another important thing that I have changed is that I am using email as the signup/login rather than the username:
Settings.py
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_UNIQUE_EMAIL = True
and my user model overwrites AbstractBaseUser like so:
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=254, null=True, blank=True)
username = models.CharField(max_length=254, blank=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
The error seems to suggest that the search algorithm is not looking in the right place for the emails. The user's email is definitely entered since I can oversee this in the admin page. why is this error occurring?
Note: this error also occurs if I use the REST browseable API so it is not linked to my form and template.
Full traceback
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/users/login/
Django Version: 2.2.5
Python Version: 3.7.3
Installed Applications:
['users.apps.UsersConfig',
'home.apps.HomeConfig',
'main.apps.MainConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount.providers.github',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_auth/views.py" in dispatch
49. return super(LoginView, self).dispatch(*args, **kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
505. response = self.handle_exception(exc)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in raise_uncaught_exception
476. raise exc
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_auth/views.py" in post
103. self.serializer.is_valid(raise_exception=True)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/serializers.py" in is_valid
235. self._validated_data = self.run_validation(self.initial_data)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation
433. value = self.validate(value)
File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_auth/serializers.py" in validate
108. email_address = user.emailaddress_set.get(email=user.email)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/ba/venv/project/lib/python3.7/site-packages/django/db/models/query.py" in get
408. self.model._meta.object_name
Exception Type: DoesNotExist at /users/login/
Exception Value: EmailAddress matching query does not exist.

You get this error because the email address you are using to login does not exist in the database table Account Email address. Dj-rest-auth or Django-rest-auth packages creates a table for Email address to track verified users.
You may run into this error when you try to login with users that are created from manage.py commands such as manage.py createsuperuser. Basically, the users created from either django admin console or management command will not create an entry in the Email address table.
To fix this error you may have to create a new entry under Accounts> Email Addresses from admin console or delete the user from Authentication and authorization> Users in admin console and register again using django-rest-auth API endpoint(which will automatically add this entry in Email Address table).

I was facing the same problem when I worked on my custom user model. The reason was that I ran python manage.py makemigrations and python manage.py migrate at the console with the default django user model first. Later, I implemented my custom user model and did the migrations.
Django documentation describes the challenge in detail:
Changing AUTH_USER_MODEL after you’ve created database tables is significantly more difficult since it affects foreign keys and many-to-many relationships, for example.
This change can’t be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations. See #25313 for an outline of the steps.
I would suggest to start with a new database, if you can. This is how i solved that issue. Otherwise try to follow this tutorial or this tutorial

i faced the same problem, it is probable you read token the bad way. for my case i used username user id , get the value with email.
So do it like that
payload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')
user = User.objects.get(id=payload['user_id'])

I hope u can fix the issue by creating a user in email address model providing the user id, email and setting verified and primary boolean fields to true; it was solved the issue for me

Related

IntegrityError exception in DeleteView CBV

I'm back with more Django Class Based View questions. I have an "extended" user model in the form of a "profile" model. The profile model is using CBVs to implement CRUD functionality but the DeleteView always generates FOREIGN KEY constraint failed IntegrityError exception. I know what that should mean but I am not sure why I am getting that exception.
I have the built-in Django user model plus an "account adaptor" and my custom Profile model. The account adaptor just sets the signup email address as the username:
class AccountAdapter(DefaultAccountAdapter):
def save_user(self, request, user, form, commit=True):
Log.add("")
data = form.cleaned_data
user.username = data['email'] # username not in use
user.email = data['email']
if 'password1' in data:
user.set_password(data['password1'])
else:
user.set_unusable_password()
self.populate_username(request, user)
if commit:
user.save()
return user
The Profile model has a OneToOneField to attach a profile instance to a user.
class Profile(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
blank=False,
null=False,
)
The DeleteView CBV is:
#method_decorator(verified_email_required, name='dispatch')
class Delete(DeleteView):
pk_url_kwarg = "account_number"
model = Profile
form_class = ProfileForm
success_url = "/accounts/logout.html"
def get(self, request, *args, **kwargs):
try:
profile = self.model.objects.get(account_number=self.kwargs[self.pk_url_kwarg])
user = User.objects.get(pk=profile.user.pk)
user.delete()
messages.success(request, "The user is deleted")
my_render = render(request, self.success_url)
except User.DoesNotExist:
messages.error(request, "User does not exist")
my_render = render(request, self.success_url)
except IntegrityError:
messages.error(request, "DB IntegrityError")
my_render = render(request, self.success_url)
return my_render
In the Delete.get method I can put a breakpoint on the user.delete() line and I can see that the profile and user objects are what I think they should be. I try to delete the user object and I get the IntegrityError exception listed above.
The stack-trace looks like:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/Members/Profile/d83622e4-4816-42a4-8419-2fd389c7e3fd/delete?csrfmiddlewaretoken=y3W0ze1SfN50Mx3eymEZQQPd21u5wjf0tHvRZM0PggLX12mdAgdEGUkw3lw2KnKn
Django Version: 2.0.3
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'auditlog',
'widget_tweaks',
'Members.apps.MembersConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'auditlog.middleware.AuditlogMiddleware']
Traceback:
File "C:\Program Files\Python36\lib\site-packages\django\db\backends\base\base.py" in _commit
239. return self.connection.commit()
The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\views\generic\base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\utils\decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\allauth\account\decorators.py" in _wrapped_view
32. return view_func(request, *args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\utils\decorators.py" in bound_func
58. return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Program Files\Python36\lib\site-packages\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:/Users/Me/PycharmProjects/MyProject/MyApp\Members\views\profile.py" in get
103. user.delete()
File "C:\Program Files\Python36\lib\site-packages\django\db\models\base.py" in delete
891. return collector.delete()
File "C:\Program Files\Python36\lib\site-packages\django\db\models\deletion.py" in delete
307. sender=model, instance=obj, using=self.using
File "C:\Program Files\Python36\lib\site-packages\django\db\transaction.py" in __exit__
212. connection.commit()
File "C:\Program Files\Python36\lib\site-packages\django\db\backends\base\base.py" in commit
261. self._commit()
File "C:\Program Files\Python36\lib\site-packages\django\db\backends\base\base.py" in _commit
239. return self.connection.commit()
File "C:\Program Files\Python36\lib\site-packages\django\db\utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Program Files\Python36\lib\site-packages\django\db\backends\base\base.py" in _commit
239. return self.connection.commit()
Exception Type: IntegrityError at /Members/Profile/d83622e4-4819-42d4-8419-2fd389c7e3fd/delete
Exception Value: FOREIGN KEY constraint failed
What am I doing wrong?
EDIT
I think my problem is with sqlite3. My DB backend is sqlite3. I have just discovered that the Django migrations that create the Profile model table DO create a foreign key reference from the profile to the User model but an on delete cascade clause is NOT created. The constraint Django creates looks like:
FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) DEFERRABLE INITIALLY DEFERRED,
I added the on delete cascade option by hand:
FOREIGN KEY(`user_id`) REFERENCES `auth_user`(`id`) on delete cascade DEFERRABLE INITIALLY DEFERRED,
but the delete operation failed as above. I dropped the DEFERRABLE INITIALLY DEFERRED clause and still get the violation.
I have a sqlite gui "management" tool and just tried to delete a user record using that management tool and get a foreign key violation as well so this must be on the sqlite side of things.
Edit 2
After more investigation I see the following: I am new to python and Django. My Django test app is really very small and I am not doing any/many custom actions. Using sqlite as the DB backend and doing the initial project makemigrations and migrate created the standard Django and django-allauth tables. There are a few of these base tables that have FOREIGN KEY relationships with the user table. My last survey of the DB was not extremely rigorous as it was really late last night ... but those that do reference the user table do not have on delete cascade clauses. So, even if I fix "my" table(s) the base Django tables that reference user seem to be "broken" by not having the cascade clause.
I will file a bug report if I can figure out where to send it.
Well, I have learned something. Django does not currently support the on delete cascade DB clause. It looks like you have to implement the behaviour yourself. I have seen posts in the email "Django Users" group about using signals for this.
I decided to try it in the DeleteView.get() method.
class Delete(DeleteView):
pk_url_kwarg = "account_number"
model = Profile
# form_class = ProfileForm
success_url = "account/login.html"
def get(self, request, *args, **kwargs):
try:
profile = get_object_or_404(Profile, account_number=self.kwargs[self.pk_url_kwarg])
user_pk = profile.user.pk
profile.delete()
get_object_or_404(User, pk=user_pk).delete()
messages.success(request, "The user is deleted")
except User.DoesNotExist:
messages.error(request, "User does not exist")
# except IntegrityError:
# messages.error(request, "DB IntegrityError")
return render(request, self.success_url)
It is possible that I don't have to actually delete the profile instance but I am still testing.

"<Association: >" needs to have a value for field "association" before this many-to-many relationship can be used: django error

I have seen a bit of similar threads here in SO but cant seem to solve it. Here is my model:
class Association(models.Model):
'''
For members declared as groups
'''
member=models.ManyToManyField(User,related_name='association_user')
name=models.CharField(max_length=50)
def __str__(self):
return self.name
class Meta:
ordering=('name',)
The many-to-many relationship ended up creating, i think, a table under the hood with the following definitions:
association_id
user_id
I don't know if it is refering to the that field association nor how to add values to that table from my views.
my forms.py
class NewAssocationForm(forms.ModelForm):
'''
this is used to create a new form
'''
class Meta:
model=Association
fields=['name',]
labels=['Assocation Name'),]
and my views.py:
#login_required
def make_new(request):
'''
Register a new association or corporate
'''
if request.method=='POST':
form=NewAssocationForm(request.POST or None)
if form.is_valid():
new_association=form.save(commit=False)
new_association.member=request.user
new_association.save()
#add a message then redirect
return HttpResponseRedirect('/corporates/done/)
else:
form=NewAssocationForm(request.POST or None)
else:
form=NewAssocationForm(request.POST or None)
return render(request, "association_new.html", locals())
I don't have a field named association in my model at all. I doubt it is constraint erorr cos i can insert records to the table from the shell without any issues.
Here is my traceback.
Environment:
Request Method: POST
Request URL: http://localhost:9000/corporates/new/
Django Version: 1.10
Python Version: 3.4.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'widget_tweaks',
'welcome',
'members',
'corporates']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\pyworks\agrigo\env\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "D:\pyworks\agrigo\env\agrigo\corporates\views.py" in make_new
78. new_association.member=request.user
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
499. manager = self.__get__(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
476. return self.related_manager_cls(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __init__
783. (instance, self.source_field_name))
Exception Type: ValueError at /corporates/new/
Exception Value: "<Association: North Side>" needs to have a value for field "association" before this many-to-many relationship can be used.
Thanks for anyone who went through the long post. Apparently, I shouldn't specify user. So, deleting the line:
new_association.member=request.user
solved the issue. Makes sense; dumb me.

KeyError 'id' when trying to access request.data in ViewSet create definition

I recently upgraded from drf 2.4 to v3 and have been trying to override the def Create in one of my ViewSets. However when trying to access the request.data that i've saved to a serializer variable i'll receive an error: KeyError at /api/appointments/
'id'
I'm including my ViewSet code, serializer, and the traceback from the error below:
class AppointmentViewSet(viewsets.ModelViewSet):
queryset = Appointment.objects.all()
serializer_class = AppointmentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def create(self, request):
serializer = AppointmentSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
#get the datetime object from the request data and filter availability objects, datetime stored in attribute .when
avQueryset = Availability.objects.filter(date__range=(serializer.data.when, serializer.data.when))
def pre_save(self, obj):
obj.service_recipient = self.request.user
Serializer
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('id','availability' , 'business_location', 'services', 'when', 'service_recipient', 'completed')
repr(serializer)
AppointmentSerializer():
id = IntegerField(label='ID', read_only=True)
availability = PrimaryKeyRelatedField(queryset=Availability.objects.all())
business_location = PrimaryKeyRelatedField(queryset=BusinessLocation.objects.all())
services = PrimaryKeyRelatedField(many=True, queryset=Service.objects.all())
when = DateTimeField(allow_null=True, required=False)
service_recipient = PrimaryKeyRelatedField(queryset=User.objects.all())
completed = BooleanField(help_text='Set to true when appointment has been completed.', required=False)
Traceback
Environment:
Request Method: POST
Request URL: http://104.131.110.138/api/appointments/
Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webapp',
'rest_framework')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/viewsets.py" in view
85. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
407. response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
404. response = handler(request, *args, **kwargs)
File "/home/appointments/appointments/webapp/views.py" in create
57. avQueryset = Availability.objects.filter(date__range=(serializer.data.when, serializer.data.when))
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
422. ret = super(Serializer, self).data
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
179. self._data = self.to_representation(self.validated_data)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in to_representation
387. attribute = field.get_attribute(instance)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/fields.py" in get_attribute
277. return get_attribute(instance, self.source_attrs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/fields.py" in get_attribute
65. instance = instance[attr]
Exception Type: KeyError at /api/appointments/
Exception Value: 'id'
You are using serializer.data when you appear to mean to be using serializer.validated_data. You should really only use serializer.data when you are looking to serialize an existing object, which would require passing an instance into the serialier when you are initializing it.
The issue is that you are not passing an instance into the serializer, so it is expecting that the initial data passed into it can be serialized. This would require the data to have all of the fields on the serializer, including id which doesn't appear to exist.
You can get the validated data, not the serialized data, using serializer.validated_data["when"]. This is specifically mentioned in the documentation for Django REST Framework under deserializing objects.

Django login Error: save() got an unexpected keyword argument 'update_fields'

Here i Create a User Manager create authentication backend but i got an error during login with manager
i create a user using AbstractBaseUser like this:
models.py
class Manager(AbstractBaseUser, PermissionsMixin):
managing_director = models.ForeignKey(ManagingDirector)
manager_name = models.CharField(max_length=50)
manager_email = models.CharField(max_length=50,null=True)
manager_mobile = models.CharField(max_length=50,null=True)
manager_address = models.TextField()
username = models.CharField(max_length=50,unique=True)
manager_status = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True)
class Meta:
verbose_name = _('Manager')
verbose_name_plural = _('Managers')
def __unicode__(self):
return self.manager_name
def get_full_name(self):
return self.manager_name
def get_short_name(self):
return self.manager_name
and i need to provide login to manager so i create a backends.py to provide
backends.py
from staffs.models import Manager
class ManagerBackend:
# Create an authentication method
# This is called by the standard Django login procedure
def authenticate(self, username=None, password=None):
try:
# Try to find a user matching your username
user = Manager.objects.get(username=username)
# Check the password is the reverse of the username
if password == user.password:
# Yes? return the Django user object
return user
else:
# No? return None - triggers default login failed
return None
except Manager.DoesNotExist:
# No user was found, return None - triggers default login failed
return None
# Required for your backend to work properly - unchanged in most scenarios
def get_user(self, user_id):
try:
return Manager.objects.get(pk=user_id)
except Manager.DoesNotExist:
return None
i add backends.mybackend.ManagerBackend in AUTHENTICATION_BACKENDS tuple in settings.py
and add staffs in installed apps
settings.py
...................
...................
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'backends.mybackend.ManagerBackend',
)
.................
.................
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
LOCAL_APPS = (
'staffs',
'products',
'distributions',
'subscriptions',
)
INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS
...............
...............
Error
TypeError at /login/
save() got an unexpected keyword argument 'update_fields'
Request Method: POST
Request URL: http://127.0.0.1:8000/login/?next=/Manager/add/
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:
save() got an unexpected keyword argument 'update_fields'
Exception Location: /home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/contrib/auth/models.py in update_last_login, line 31
Python Executable: /home/node1/Office/projectenv/bin/python
Python Version: 2.7.3
Python Path:
['/home/node1/Office/projects.inzane/smedia/smedia',
'/home/node1/Office/projectenv/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/home/node1/Office/projectenv/local/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg',
'/home/node1/Office/projectenv/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/home/node1/Office/projectenv/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg',
'/home/node1/Office/projectenv/lib/python2.7',
'/home/node1/Office/projectenv/lib/python2.7/plat-linux2',
'/home/node1/Office/projectenv/lib/python2.7/lib-tk',
'/home/node1/Office/projectenv/lib/python2.7/lib-old',
'/home/node1/Office/projectenv/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/home/node1/Office/projectenv/local/lib/python2.7/site-packages',
'/home/node1/Office/projectenv/local/lib/python2.7/site-packages/PIL',
'/home/node1/Office/projectenv/lib/python2.7/site-packages',
'/home/node1/Office/projectenv/lib/python2.7/site-packages/PIL']
Server time: Sat, 13 Jul 2013 06:56:46 -0500
Traceback
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/login/?next=/Manager/add/
Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'staffs',
'products',
'distributions',
'subscriptions')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
69. return view(request, *args, **kwargs)
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/contrib/auth/views.py" in login
46. auth_login(request, form.get_user())
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
95. user_logged_in.send(sender=user.__class__, request=request, user=user)
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py" in send
170. response = receiver(signal=self, sender=sender, **named)
File "/home/node1/Office/projectenv/local/lib/python2.7/site-packages/django/contrib/auth/models.py" in update_last_login
31. user.save(update_fields=['last_login'])
Exception Type: TypeError at /login/
Exception Value: save() got an unexpected keyword argument 'update_fields'
As you can see that error is caused by the line
user.save(update_fields=['last_login'])
Method save is inherited from models.Model class (via AbstractBaseUser) which does not accept keyword arguments.
I can suggest any solution to you as I do not know that functionality you require. But if you do not need save any changes to db as I do you can simply override this method to accept keyword arguments and do nothing
def save (self, *args, **kwargs):
"""saving to DB disabled"""
pass

error in admin page when editing using django-multilingual-ng on django 1.3

am trying to switch my application to use multilingual-ng, unfortunutely though, there is very little documentation and FAQ's online. I hope someone would be able to tell what is going on with my practice,
following is my model
class Main(models.Model):
""" Main Class for all categories """
slug = models.SlugField()
is_active = models.BooleanField(default=True)
site = models.ForeignKey(Site)
parent = models.ForeignKey('self', blank=True, null=True)
class Translation(TranslationModel):
title = models.CharField(max_length=100)
label = models.CharField(max_length=100, blank=True, null=True)
description = models.TextField(blank=True, null=True)
disclaimer = models.TextField(blank=True, null=True)
class Meta:
unique_together = (("slug", "parent"))
def __unicode__(self):
return self.title if self.title is not None else _("No translation")
and following is my admin.py
class MainAdmin(MultilingualModelAdmin):
''' Multilingual interface for Main category '''
class ListAdmin(MultilingualModelAdmin):
''' Multilingual interface for Main category '''
admin.site.register(Main, MainAdmin)
admin.site.register(List, ListAdmin)
When I access my admin panel, I can see the model, list of items, add new items but when I try to edit an existing item or delete one I get the followng error
Environment:
Request Method: GET
Request URL: http://mazban.com/admin/category/main/1/
Django Version: 1.3
Python Version: 2.6.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'compressor',
'django.contrib.gis',
'multilingual',
'mazban.lib.apps.core',
'mazban.lib.apps.gis',
'mazban.apps.global',
'mazban.apps.listing',
'mazban.apps.listing.post',
'mazban.apps.listing.home',
'mazban.apps.listing.engine',
'mazban.apps.listing.category']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'mazban.lib.MiddleWare.custom.RequestIsMobile')
Traceback:
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/contrib/admin/options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/contrib/admin/sites.py" in inner
197. return view(request, *args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/multilingual/admin.py" in wrapped
31. resp = func(cls, request, *args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/multilingual/admin.py" in change_view
277. return super(MultilingualModelAdmin, self).change_view(*args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/utils/decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/utils/decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/db/transaction.py" in inner
217. res = func(*args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/contrib/admin/options.py" in change_view
947. obj = self.get_object(request, unquote(object_id))
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/contrib/admin/options.py" in get_object
451. return queryset.get(pk=object_id)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/db/models/query.py" in get
341. clone = self.filter(*args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/db/models/query.py" in filter
550. return self._filter_or_exclude(False, *args, **kwargs)
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/db/models/query.py" in _filter_or_exclude
568. clone.query.add_q(Q(*args, **kwargs))
File "/users/mo/Projects/python-envs/mazban/lib/python2.6/site-packages/django/db/models/sql/query.py" in add_q
1172. can_reuse=used_aliases, force_having=force_having)
Exception Type: TypeError at /admin/category/main/1/
Exception Value: add_filter() got an unexpected keyword argument 'force_having'
Don't use django-multilingual-ng, as it is not supported anymore and will bring you many headaches. The author of the django-multilingual-ng started a new promising project, named django-nani. It should be reliable and Django 1.3 compatible.
As for me, this problem didn't show on Django 1.2.4, so you might want to move back to that version, once you go through the Django 1.2.5 release notes.
I installed from latest revision and the error disapeared:
$ pip install git+https://github.com/ojii/django-multilingual-ng.git
Although the error is gone using this release, it still says it it unsupported. I am heavily inclined to roll back to Django 1.2.4, but I am still trying to figure this out.
As mentioned, the django-nani project is promising, but it is still in alpha stages. I couldn't find a way to work with any type of model relationship as of today's revision. They will be working on it soon.
I've got the same problem, upgrading from 1.2.4 to the new security releases in 1.2.7. Ng is already in use and can't be swapped out, even though support for it has been dropped. Just the world we live in. I can't find any documentation on force_havings role in the django query system.
Glad they're working on a new system though. If anyone has any knowledge on force_having it would be greatly appreciated.