IntegrityError exception in DeleteView CBV - django

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.

Related

user_change_password() got an unexpected keyword argument 'extra_context'

Django 3.0.7
When I try to change password in admin site, I get
TypeError at /admin/auth/user/1/password/
user_change_password() got an unexpected keyword argument 'extra_context'
Namely I pressed "this form" link:
More details
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/auth/user/1/password/
Django Version: 3.0.7
Python Version: 3.8.0
Installed Applications:
['admin_aux',
'images.apps.ImagesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
'sidebars',
'general',
'categories',
'marketing',
'home',
'authors',
'taggit',
'cachalot',
'django_cleanup.apps.CleanupConfig',
'widgets',
'code_samples',
'hyper_links',
'polls',
'applications',
'videos',
'quotations',
'languages',
'people',
'arbitrary_htmls.apps.ArbitraryHtmlsConfig']
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 (most recent call last):
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
Exception Type: TypeError at /admin/auth/user/1/password/
Exception Value: user_change_password() got an unexpected keyword argument 'extra_context'
How can I localize this problem?
What's happening...
I have no idea tbh. It is worth noting a few things though, that the url, should call a method in the User Auth ModelAdmin at django/contrib/auth/admin called user_change_password. It has the following signature:
def user_change_password(self, request, id, form_url=""):
which is why the error is being raised, because somehow extra_context is being passed to it.
There is also a way for you to change the logged on users password, which does accept a extra_context kwarg. My best guess is that one of the apps has overwritten the standard auth ModelAdmin and done it not quite right. Certainly everything works fine with a fresh django 3.0.7 project.
How can I localize this problem?
I would remove all of your additional apps. Hopefully this will fix the problem. If it doesn't then this becomes more interesting. But if it does, I would add them back in one by one until it breaks, and then you'll figure out which additional app is breaking things.
maybe you even can help me cope with it.
There's a few things I can think of that you could do if you just want to change the password. You can change user details via the shell:
python manage.py shell
Then the following will enable you to change a password:
from auth.models import User
user = User.objects.get(id=1) # Or whatever user you want
user.set_password('my_new_password')
user.save()
This should do the trick. Even easier still, there is a management command that does it (but for this you will need to know the current password). You can simply run:
manage.py changepassword *username*
I had this issue (though in Django 2.2). It started after I took the advice from another Stack Overflow post on adding extra_context to every admin page. This seems harmless, but breaks the "change password" form. In the end I deleted the 'extra_context' changes to urls.py and added the extra_context ONLY to the admin forms I needed using the ModelAdmin add_view and change_view methods.
# New Layer Form
def add_view(self, request, form_url='', extra_context={}):
extra_context['CATALOG_TECHNOLOGY'] = settings.CATALOG_TECHNOLOGY
return super(LayerAdmin, self).add_view(request, form_url, extra_context)
# Edit Layer Form
def change_view(self, request, object_id, extra_context={}):
extra_context['CATALOG_TECHNOLOGY'] = settings.CATALOG_TECHNOLOGY
return super(LayerAdmin, self).change_view(request, object_id, extra_context=extra_context)
Here are the commits for full context:
Breaking Commit
urls.py
Fixing Commits
urls.py
admin.py

Django REST EmailAddress matching query does not exist

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

MultiValueDictKeyError when deleting related inline records in another tab

I'll try to be as concise as possible.
Background
I have a model Person which has a ForeignKey to model Document. Each Person can only have one Document but, as you may already know, each Document can be linked to many Persons.
In the Document's Admin form I have the Persons associated to the Document displayed inline. I can edit, add or delete the Persons right there.
Problem
Following these steps I get the error:
I open the Admin edit form for a Document. Let's call it Document
A. This Document has two Persons associated, let's call them John
Doe and Jane Doe. You can see them there (inline) in the form and
the fields are editable, but I don't touch them.
I open another tab and go straight to the Persons list and delete
Jane Doe.
I get back to the first tab (the Document's edit form) and click on
"Save and continue editing".
The form is sent and I get a generic error at the top (something
like) "Please, fix the following errors". But the form shows no
errors (next to the fields) to correct and, obviously, the record
for Jane Doe isn't displayed.
I click again on "Save and continue editing" and when the form is
sent I get the error "MultiValueDictKeyError: "u'person_set-1-id'"".
Ideal solution
I'd like to be able to display a custom error in the middle stage (when the first error appears, after the first save), saying something like "A person associated with this Document was deleted while you were editing it". Also, preventing the final error is highly desirable.
Error dump
MultiValueDictKeyError at /admin/persons/document/1145/
"u'person_set-1-id'"
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Exception Type: MultiValueDictKeyError
Exception Value:
"u'person_set-1-id'"
Exception Location: /__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py in __getitem__, line 319
Python Executable: /__PATH__/bin/python
Python Version: 2.7.15
Python Path:
['/__PATH__/test/test/apps',
'/__PATH__/test',
'/__PATH__/lib/python2.7',
'/__PATH__/lib/python2.7/plat-x86_64-linux-gnu',
'/__PATH__/lib/python2.7/lib-tk',
'/__PATH__/lib/python2.7/lib-old',
'/__PATH__/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/__PATH__/local/lib/python2.7/site-packages',
'/__PATH__/src/django-smart-selects',
'/__PATH__/lib/python2.7/site-packages',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/test']
Server time: Mar, 29 Ene 2019 11:52:18 -0300
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Python Version: 2.7.15
Installed Applications:
('salmonella',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'crispy_forms',
'test.apps.persons',
'captcha',
'django_countries',
'django_extensions',
'import_export',
'django_object_actions',
'widget_tweaks',
'smart_selects',
'daterange_filter',
'compressor',
'auditlog')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'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 "/__PATH__/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
583. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
206. return view(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
1456. return self.changeform_view(request, object_id, form_url, extra_context)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/__PATH__/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1403. if all_valid(formsets) and form_validated:
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in all_valid
438. if not formset.is_valid():
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in is_valid
303. self.errors
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in errors
277. self.full_clean()
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in full_clean
325. form = self.forms[i]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/functional.py" in __get__
55. res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in forms
141. forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
868. form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
581. pk = self.data[pk_key]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py" in __getitem__
319. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /admin/persons/document/1145/
Exception Value: "u'person_set-1-id'"
UPDATE
I'm adding the definitions for models Person and Document.
class Document(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=300, null=True, blank=True)
class Person(models.Model):
first_name = models.CharField(max_length=300)
last_name = models.CharField(max_length=300)
email = models.EmailField(max_length=300)
document = models.ForeignKey(Document)
UPDATE 2
One important thing I noticed is that, in the first error page (after the first submission of Document A form) the hidden inputs like person_set-TOTAL_FORMS and person_set-INITIAL_FORMS are set to 2 while they should be set to 1 (the actual number of persons). Obviously this happens because the submitted data doesn't reflect the actual database state.

Integrity Error May not be null

I am building a website similar to a bartering website, but we are bartering Time,
I have a class Transaction, where it takes the "offer" value, deductions that value from the balance of the requesting user, and credits the value to the Offer'r.
Right now when I click on "Accept Offer" from my template I get this error
ofertoj_transaction.accepted_by may not be NULL
Stacktrace:
IntegrityError at /oferto/accept/
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/oferto/accept/?offer_id=1&creator=2
Django Version: 1.5.4
Python Version: 2.7.4
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',
'django.contrib.comments',
'django.contrib.sitemaps',
'zinnia',
'tagging',
'mptt',
'south',
'registration',
'blogs',
'turtle',
'ofertoj',
'petoj',
'x',
'profiles')
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.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/talisman/projects/tempilo/ofertoj/views.py" in get
74. accepted_by=self.request.user.id
File "/home/talisman/projects/tempilo/ofertoj/models.py" in create
59. new_transaction.save()
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/base.py" in save_base
650. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/manager.py" in _insert
215. return insert_query(self.model, objs, fields, **kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/query.py" in insert_query
1675. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
937. cursor.execute(sql, params)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/util.py" in execute
41. return self.cursor.execute(sql, params)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
364. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
362. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /oferto/accept/
Exception Value: ofertoj_transaction.accepted_by may not be NULL
part of ofertoj.views.py
class TransactionView(TemplateView, LoginRequiredMixin):
template_name = "ofertoj/offer_accepted.html"
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if self.request.GET.get("offer_id"):
oferto = Oferto.objects.get(id=self.request.GET.get("offer_id"))
if oferto.valid:
transaction = Transaction()
transaction.create(
creator=self.request.GET.get("creator"),
amount=oferto.time,
accepted_by=self.request.user.id
)
acceptor = Profile.objects.get(user=self.request.user)
acceptor.balance = acceptor.balance - oferto.time
acceptor.save()
# credit the coins to the creator
creator = Profile.objects.get(user=oferto.user)
creator.balance = creator.balance + oferto.time
creator.save()
else:
return HttpResponse("This offer is already accepted")
else:
raise Http404
return self.render_to_response(context)
Part of Ofertoj.models
class Transaction(models.Model):
creator = models.IntegerField()
amount = models.IntegerField()
accepted_by = models.IntegerField()
def __unicode__(self):
return self.id
def create(self, **kwargs):
new_transaction = Transaction(
creator = kwargs['creator'],
amount = kwargs['amount'],
accepted_by = kwargs['accepted_by']
)
new_transaction.save()
return
this line is highlited in the stacktrace
acceptor = Profile.objects.get(user=self.request.user)
ofertoj.urls
url(
regex=r"^accept/$",
view = TransactionView.as_view(),
name = "accept_offer"
),
part of my template
{% if oferto.valid and not oferto.user == request.user %}
Accept this Offer
{% endif %}
<br /><br />
Your ofertoj application is trying to store a Transaction object which has an accepted_by field which is NULL but your database schema does not allow this field to be NULL.
Check this code:
transaction.create(
creator=self.request.GET.get("creator"),
amount=oferto.time,
accepted_by=self.request.user.id
)
and the code of transaction.create.
One possibility: if your user is not logged in then self.request.user.id will be None, and this translates to NULL in the database. I do not see anything in your code that requires the user to be logged in.
it was an issue with unicode method in the Profile model
and since, the balance was default null

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.