Django unique constraint not working - django

I want to display error whenever user try to create object with the same name. I want firm name to be unique. Tried but issue remains. Django should display error in the form but why I am getting this.????
Firm model:
class Firm(models.Model):
name = models.TextField(
verbose_name='firm name',
max_length=100, unique=True
)
address = models.TextField(
max_length=100
)
phone_no_1 = models.CharField(
max_length=10, null=True, blank=True
)
phone_no_2 = models.CharField(
max_length=10, null=True, blank=True
)
reg_no = models.TextField(
max_length=25, null=True, blank=True
)
But instead I am getting this.
Traceback:
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\utils\decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\utils\decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Users\PrImE\workspace\kaizentech\egirvi\dev\egirvi\girvi\utils.py" in dispatch
14. return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\edit.py" in post
207. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\edit.py" in post
173. return self.form_valid(form)
File "C:\Users\PrImE\workspace\kaizentech\egirvi\dev\egirvi\girvi\views\create_views\create_firm_view.py" in form_valid
16. super(CreateFirmView, self).form_valid(form)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\edit.py" in form_valid
149. self.object = form.save()
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\forms\models.py" in save
457. construct=False)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\forms\models.py" in save_instance
103. instance.save()
File "C:\Users\PrImE\workspace\kaizentech\egirvi\dev\egirvi\girvi\models\firm.py" in save
29. return super(Firm, self).save(*args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in save
590. force_update=force_update, update_fields=update_fields)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in save_base
618. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in _save_table
699. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in _do_insert
732. using=using, raw=raw)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\query.py" in _insert
921. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
920. cursor.execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\utils.py" in execute
81. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
485. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /add_firm/
Exception Value: column name is not unique
View:
class CreateFirmView(LoginRequiredMixin, CreateView):
form_class = CreateFirmForm
http_method_names = ['get', 'post']
success_url = reverse_lazy('girvi:find_customer')
template_name = 'create_templates/create_firm.html'
def form_valid(self, form):
from django.shortcuts import HttpResponse
super(CreateFirmView, self).form_valid(form)
return HttpResponse(
'''
<script>
window.close();
window.onunload = refreshParent; function refreshParent() {
window.opener.location.reload();
}
</script>
'''
)
Form:
class CreateFirmForm(forms.ModelForm):
from girvi.utils import validators
phone_no_1 = forms.CharField(
label='Phone No. 1', required=False, validators=[
validators.get('only_numbers'), validators.get('min_value')(10)
],
widget=forms.TextInput(
attrs={'placeholder': 'Mobile Number', 'class': 'form-control'}
)
)
phone_no_2 = forms.CharField(
label='Phone No. 2 ', required=False, validators=[
validators.get('only_numbers'), validators.get('max_value')(10), validators.get('max_value')(10)
],
widget=forms.TextInput(
attrs={'placeholder': 'Mobile Number', 'class': 'form-control'}
)
)
class Meta:
model = Firm
fields = '__all__'
widgets = {
'name': forms.TextInput(
attrs={'autofocus': 'true', 'class': 'form-control', 'placeholder': 'Firm Name'}
),
'address': forms.TextInput(
attrs={'class': 'form-control', 'placeholder': 'Address'}
),
'reg_no': forms.TextInput(
attrs={'class': 'form-control', 'placeholder': 'Reg No.'}
)
}
SQL :
CREATE TABLE "girvi_firm" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(100) NOT NULL UNIQUE, "address" text NOT NULL, "phone_no_1" varchar(10) NULL, "phone_no_2" varchar(10) NULL, "reg_no" text NULL)

This error is thrown by database.
But django ModelForm will process unique costraint automatically.
Just don't forget to call clean() method of the parent form:
from django import forms
class FirmForm(forms.ModelForm):
class Meta:
model = Firm
def clean(self):
# do some your stuff here
# don't forget to call super().clean
return super(FirmForm, self).clean()
As it written in django docs:
The ModelForm.clean() method sets a flag that makes the model validation step validate the uniqueness of model fields that are marked as unique, unique_together or unique_for_date|month|year.
If you would like to override the clean() method and maintain this validation, you must call the parent class’s clean() method.

Related

Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name

Im Created 2 Models.
Account
UserProfil
First Of All, User Register email, fullname, password1, password2. The data Sending To Database in table Account.
Second, User Will Login, if success, he will go to dashboard. in dashboard have a profil Form.
In The Profil Form, He Will input data profil, likes number phone, birth date. etc. and will store in table UserProfil
All of data in UserProfil relationship with Account.
Im Try to create 'Profil Form'. Like This.
my Question is How To Put the data Full_Name in this form ?
i got Error Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name ...
authentication/models.py
class Account(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
full_name = models.CharField(max_length=150)
create_account = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_reviewer = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name']
def __str__(self):
return self.full_name
dashboard/models.py
class UserProfil(models.Model):
jenis_kelamin_choice = (
('Pria', 'Pria'),
('Wanita', 'Wanita' ),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
nik = models.CharField(max_length=11, null=True, unique=True)
nidn = models.CharField(max_length=11, null=True, unique=True)
def __str__(self):
return str(self.user)
dashboard/views.py
class UserProfilFormView(CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
userPofil = form.save(commit=False)
userPofil.user = Account.objects.get(user__full_name=self.request.user)
userPofil.save()
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
File Traceback :
Internal Server Error: /dashboard/profil
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "D:\Project\hibahinternal\dashboard\views.py", line 26, in
form_valid
userPofil.user = Account.objects.get(user__full_name=self.request.user)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 424, in get
clone = self._chain() if self.query.combinator else self.filter(*args,
**kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 968, in
_filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1286, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1112, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted,
self.get_meta())
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1539, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'user' into
field. Choices are: create_account, email, full_name, groups, id,
is_active, is_admin, is_reviewer, is_staff, is_superuser, last_login,
logentry, password, user_permissions, userprofil
[20/Dec/2021 19:31:48] "POST /dashboard/profil HTTP/1.1" 500 136397
Thanks
Your Account has no user field, this also would not make much sense, since that is the user account. You do not need to make a query to the Account model anyway: request.user works with the user model, here account, so you can use request.user directly:
from django.contrib.auth.mixins import LoginRequiredMixin
class UserProfilFormView(LoginRequiredMixin, CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
form.instance.user = request.user
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Custom User model error on changing password form through admin interface

Trying to set up custom user model on the start of django project, but i am facing a recurrent problem that i have only been able to patch, that now is affecting the changepassword of admin interface. On change password form submit, it crashes with error:
AttributeError at /admin/custom_users/customuser/7/password/
'NoneType' object has no attribute 'strip'
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/custom_users/customuser/7/password/
Django Version: 2.2
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cashflow.apps.CashflowConfig',
'custom_users.apps.CustomUsersConfig']
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 "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/connection_cext.py" in cmd_query
395. raw_as_string=raw_as_string)
During handling of the above exception (Column 'is_superuser' cannot be null), another exception occurred:
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in _execute_wrapper
168. return method(query, args)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in execute
266. raw_as_string=self._raw_as_string)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/connection_cext.py" in cmd_query
398. sqlstate=exc.sqlstate)
During handling of the above exception (1048 (23000): Column 'is_superuser' cannot be null), another exception occurred:
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
99. return super().execute(sql, params)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
76. return executor(sql, params, many, context)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute
84. return self.cursor.execute(sql, params)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in execute
218. return self._execute_wrapper(self.cursor.execute, query, new_args)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in _execute_wrapper
174. utils.IntegrityError(err.msg), sys.exc_info()[2])
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/utils/six.py" in reraise
683. raise value.with_traceback(tb)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in _execute_wrapper
168. return method(query, args)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in execute
266. raw_as_string=self._raw_as_string)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/connection_cext.py" in cmd_query
398. sqlstate=exc.sqlstate)
During handling of the above exception (Column 'is_superuser' cannot be null), another exception occurred:
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in statement
606. return self._executed.strip().decode('utf8')
During handling of the above exception ('NoneType' object has no attribute 'strip'), another exception occurred:
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/contrib/auth/admin.py" in user_change_password
141. form.save()
File "/home/mh/devel/dreamit_control/dcontrol/custom_users/forms.py" in save
32. self.user.save()
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/contrib/auth/base_user.py" in save
66. super().save(*args, **kwargs)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in save
741. force_update=force_update, update_fields=update_fields)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in save_base
779. force_update, using, update_fields,
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in _save_table
851. forced_update)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/base.py" in _do_update
900. return filtered._update(values) > 0
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/query.py" in _update
760. return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1426. cursor = super().execute_sql(result_type)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1097. cursor.execute(sql, params)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
103. sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/operations.py" in last_executed_query
127. return force_text(cursor.statement, errors='replace')
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/django/base.py" in __getattr__
230. return getattr(self.cursor, attr)
File "/home/mh/devel/dreamit_control/env/lib/python3.7/site-packages/mysql/connector/cursor_cext.py" in statement
608. return self._executed.strip()
Exception Type: AttributeError at /admin/custom_users/customuser/7/password/
Exception Value: 'NoneType' object has no attribute 'strip'
on stack trace, i can see that the problem is that is_staff=NULL and is_superuser=NULL on the attempted query.
I dont know why django passes this parameters as null on passwordchange since they are set to false on model and nowhere are they as fields on the CustomUserPassForm. Had this same issue on user change form, but after adding fieldsets to CustomUserAdmin(UserAdmin) class, i was able to edit a user. (as the is_superuser and is_staff input checkboxes appeared on form in html)
models.py
class CustomUserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('correo es obligatorio')
email = self.normalize_email(email)
extra_fields.setdefault('is_superuser', False)
extra_fields.setdefault('is_staff', False)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('superuser must have is_staff=True')
if extra_fields.get('is_superuser') is not True:
raise ValueError('superuser musthave is_superuser=True')
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractUser, PermissionsMixin):
cargo = models.TextField(max_length=50, null=True)
rut = models.IntegerField(null=True)
DIGITO_VERIFICADOR_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
('8','8'),
('9','9'),
('0','0'),
('K','K')
)
digito_verificador = models.CharField(max_length=1, choices=DIGITO_VERIFICADOR_CHOICES, null=True)
nombre = models.CharField(max_length=25, default="john")
apellido = models.CharField(max_length=25, default="doe")
email = models.EmailField(verbose_name='correo', max_length=255, unique=True)
username = models.TextField(max_length=255, null=True)
is_superuser = models.BooleanField(default=False, blank=True)
is_staff = models.BooleanField(default=False, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = get_user_model()
fields = ['email', 'rut', 'digito_verificador',]
class CustomUserChangeForm(UserChangeForm):
rut = forms.IntegerField(min_value=1000000)
#is_superUser = forms.BooleanField()
class Meta:
model = get_user_model()
fields = ['rut', 'digito_verificador',]
#['email', 'is_superuser','is_staff' ]
class CustomUserPassForm(AdminPasswordChangeForm):
# is_staff = forms.BooleanField(initial=False)
# is_superuser = forms.BooleanField(initial=False)
#fields = ['is_staff','is_superuser']
def save(self, commit=True):
password = self.cleaned_data["password1"]
self.user.set_password(password)
print(self.user)
if commit:
self.user.save()
return self.user
admin.py
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
change_password_form = CustomUserPassForm
model = get_user_model()
list_display = ['email', ]
fieldsets = (
(None, {'fields': ('email', 'password')}),
('personal info',{'fields': ('nombre', 'apellido',('rut','digito_verificador'))}),
('permissions', {'fields':('is_superuser', 'is_staff')})
)
add_fieldsets = (
(None, {
'classes':('wide',),
'fields':('email', 'password1', 'password2'),
}
),
)
admin.site.register(CustomUser, CustomUserAdmin)
Have been two days reading tutorials and documentation, including official django guide, all which leave out any information about implementation of change_password_form.
The problem was the save method of the CustomUserPassForm. For some reason (i havent done the complete followup) the user attribute had is_staff and is_superuser set to NULL. forcing these to false patched the problem.
class CustomUserPassForm(AdminPasswordChangeForm):
def save(self, commit=True):
password = self.cleaned_data["password1"]
self.user.set_password(password)
self.user.is_staff = False
self.user.is_superuser = False
if commit:
self.user.save()
return self.user
Now if anyone can shed some light as to why, i'd be appreciated (also, how to set the is_staff and is_superuser to the same value that is actually held in db.)

Updating user information with extending fields on one page

I want to update current user profile. User has one-to-one UserExtend model, so I would like to update the extending fields on the same submit event as well.
class UserExtend(models.Model):
user = models.OneToOneField(User)
town = models.CharField(max_length=100, blank=True)
age = models.IntegerField(blank=True)
organization = models.CharField(max_length=100, blank=True)
tel = models.CharField(max_length=15, blank=True)
def __unicode__(self):
return unicode(self.user)
Here is my views.py
def ProfileUpdateView(request):
user = request.user
user_form = UserForm(request.POST or None, initial={
'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email
})
user_extend_form = UserExtendForm(request.POST or None, initial={
'user': user,
})
contacts = Contact.objects.get(activity=True)
tels = contacts.tel.all()
bg = Background.objects.get(activity=True)
botlinks = Bottom_navigation.objects.all()
if user_form.is_valid() and user_extend_form.is_valid():
user_form.save()
user_extend_form.save()
c = {'form': user_form, 'extend_form': user_extend_form, 'contacts': contacts, 'tels': tels, 'bg': bg,
'botlinks': botlinks}
return render(request, 'posts/user_form.html', c)
and forms.py
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
class UserExtendForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.all(),widget=forms.HiddenInput())
class Meta:
model = UserExtend
fields = '__all__'
As it can be seen, I decided not to rewrite my ModelForm def function, but to pass two forms in a template with one submit button. Everything is rendered as expected, however when I click the submit I get an error like this:
Traceback:
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/srv/webapps/saunaflame/core/posts/views.py" in ProfileUpdateView
89. user_form.save()
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/forms/models.py" in save
463. construct=False)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/forms/models.py" in save_instance
105. instance.save()
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in save
710. force_update=force_update, update_fields=update_fields)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
738. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
822. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
861. using=using, raw=raw)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
127. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
920. return query.get_compiler(using=using).execute_sql(return_id)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
974. cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
97. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
124. return self.cursor.execute(query, args)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/MySQLdb/cursors.py" in execute
205. self.errorhandler(self, exc, value)
File "/srv/webapps/saunaflame/local/lib/python2.7/site-packages/MySQLdb/connections.py" in defaulterrorhandler
36. raise errorclass, errorvalue
Exception Type: IntegrityError at /posts/profile/update/
Exception Value: (1062, "Duplicate entry '' for key 'username'")
Why django is trying to overwrite the username field for my User instance if I do not pass it to the form?
And is there a better way to update user info with extending fields on a single page?
Thanx.
This has nothing to do with having two forms. It's because you're passing initial values, then saving the form, so it's naturally trying to create a new instance with those values, even though they conflict with existing data.
You should be using the instance parameter instead of initial, so that Django knows to update the existing instances.
user_form = UserForm(request.POST or None, instance=request.user)
user_extend_form = UserExtendForm(request.POST or None, instance=request.user.userextend)

Django IntegrityError error

Getting IntegrityError if I try to enter data through CBV CreateView but everything works fine through admin panel.
Model:
class Account(Info):
firm = models.ForeignKey(
Firm
)
name = models.CharField(
max_length=100
)
is_default = models.BooleanField(
default=False
)
type = models.CharField(
max_length=1, choices=ACCOUNT_TYPE_CHOICES
)
category = models.CharField(
max_length=1, choices=ACCOUNT_CATEGORIES
)
sub_category = models.CharField(
max_length=1, choices=ACCOUNT_SUB_CATEGORIES
)
show_in = models.CharField(
max_length=1, choices=SHOW_IN
)
class Meta:
ordering = [
'name'
]
unique_together = (
'firm', 'name'
)
View:
class CreateAccountView(LoginRequiredMixin, CreateView):
success_url = '/'
form_class = CreateAccountForm
http_method_names = ['get', 'post']
template_name = 'create_templates/create_account.html'
def get_context_data(self, **kwargs):
context = super(CreateAccountView, self).get_context_data(**kwargs)
firm_obj = self.get_firm_obj(self.kwargs.get('f_id'))
context['firm_obj'] = firm_obj
return context
def form_valid(self, form):
form.instance.firm = self.get_firm_obj(self.kwargs.get('f_id'))
form.instance.is_default = False
form.instance.sub_category = '4'
super(CreateAccountView, self).form_valid(form)
return HttpResponse(
'''
<script>
window.close();
window.onunload = refreshParent; function refreshParent() {
window.opener.location.reload();
}
</script>
'''
)
#staticmethod
def get_firm_obj(f_id):
return get_object_or_404(Firm, id=f_id)
Form:
class CreateAccountForm(forms.ModelForm):
name = forms.CharField(
label='Account Name', max_length=100,
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
class Meta:
model = Account
fields = (
'name', 'type',
'category', 'show_in'
)
widgets = {
'type': forms.Select(
attrs={
'class': 'form-control'
}
),
'category': forms.Select(
attrs={
'class': 'form-control'
}
),
'show_in': forms.Select(
attrs={
'class': 'form-control'
}
)
}
Traceback:
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\utils\decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\utils\decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Users\PrImE\workspace\kaizentech\emuneem\emuneem\girvi\utils.py" in dispatch
17. return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\edit.py" in post
207. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\edit.py" in post
173. return self.form_valid(form)
File "C:\Users\PrImE\workspace\kaizentech\emuneem\emuneem\muneem\views\create_views\create_account_view.py" in form_valid
25. super(CreateAccountView, self).form_valid(form)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\views\generic\edit.py" in form_valid
149. self.object = form.save()
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\forms\models.py" in save
457. construct=False)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\forms\models.py" in save_instance
103. instance.save()
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in save
590. force_update=force_update, update_fields=update_fields)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in save_base
618. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in _save_table
699. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\base.py" in _do_insert
732. using=using, raw=raw)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\query.py" in _insert
921. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
920. cursor.execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\utils.py" in execute
81. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Users\PrImE\envs\kaizentech\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
485. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /add_account/f/1/
Exception Value: columns firm_id, name are not unique
Using sqlite for development. Everything is working fine through admin panel if I try to enter duplicate entry through admin panel I get Account with this Firm and Name already exists. which is correct but why I'm not seeing this error via CBV
You've excluded firm from the form, and don't add it until after validation, so there's no way the form can validate that the combination of firm and name is unique. You'll need to pass it int the form some other way and check explicitly in the form's clean method that there is no existing instance with that combination.
This definition means "Account with this Firm and Name already exists." You are receiving the same error in both cases,
unique_together = (
'firm', 'name'
)
Exception Value: columns firm_id, name are not unique, that means the same as the admin panel error.

Django: Adding "created by" field to object

I need to store the user who is creating a specific object in the database, like so:
(models.py)
class Address(models.Model):
createdBy = models.ForeignKey(User)
address1 = models.CharField("Address Line 1", max_length=40)
address2 = models.CharField("Address Line 2", max_length=40, blank=True)
city = models.CharField(max_length=20)
state = models.CharField(max_length=3)
zipCode = models.CharField("Postal Code", max_length=10)
My view for handling the form is here (views.py):
def handlePopAdd(request, addForm, field):
if request.method == "POST":
form = addForm(request.POST)
if form.is_valid():
try:
newObject = form.save(request)
except forms.ValidationError, error:
newObject = None
if newObject:
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>'% (escape(newObject._get_pk_val()), escape(newObject)))
else:
form = addForm()
pageContext = {'form': form, 'field': field}
return render_to_response("address_popup.html", pageContext, context_instance=RequestContext(request))
And finally, here is my form code: (forms.py)
class AddressForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(AddressForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
obj = super(AddressForm, self).save(commit=False)
if self.request:
obj.createdBy = self.request.user
obj.save()
class Meta:
model = Address
exclude = ('createdBy',)
I am using the top answer suggested by this question, and have hit a wall after a few hours staring a hole through this.
Here's my traceback. Error is IntegrityError at /app/address/add/ (1048, "Column 'createdBy_id' cannot be null")
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/home/matthew/lessonhelper/../lessonhelper/lessons/views.py" in address_add
78. return handlePopAdd(request, AddressForm, 'address')
File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/home/matthew/lessonhelper/../lessonhelper/lessons/views.py" in handlePopAdd
66. newObject = form.save(request)
File "/home/matthew/lessonhelper/../lessonhelper/lessons/forms.py" in save
29. obj.save()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py" in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py" in save_base
553. result = manager._insert(values, return_id=update_pk, using=using)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py" in _insert
195. return insert_query(self.model, values, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in insert_query
1436. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
791. cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
735. cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py" in execute
34. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/mysql/base.py" in execute
86. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py" in execute
166. self.errorhandler(self, exc, value)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in defaulterrorhandler
35. raise errorclass, errorvalue
Exception Type: IntegrityError at /app/address/add/
Exception Value: (1048, "Column 'createdBy_id' cannot be null"
You specifically defined logic to add the request to the form, but are not using it.
You need to instantiate your form with request as a keyword argument (according to your code).
form = addForm(request.POST, request=request)
save(request) does nothing with the request.
Most people prefer just accepting a new argument in save().
def save(self, request):
obj = super(AddressForm, self).save(commit=False)
obj.createdBy = request.user
obj.save()
Finally, there's no point in the if block in the save method if createdBy is not nullable: it's required. There's no "if" about it.
You excluded the createdBy field in your form and according to your Model definition, it's a required field since you're using a ModelForm.