Django IntegrityError error - django

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.

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].

Adding context to a Class Based View (detail view) geting an error get_context_data() got an unexpected keyword argument 'object'

I am trying to learn how to add a 2nd Context to a Class-Based view which has always been an issue for me and I can't get it right from the first time.
In my current project, I am trying to add a comment section to item detail view.
I am currently getting an error of get_context_data() got an unexpected keyword argument 'object'
which is from the item detail view as I indicated and I don't know who to fix it
Here is the item model:
class Item(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
here is the comment model:
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments")
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{} by {}'.format(self.subject, str(self.user.username))
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment']
here is the view:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(request, id):
context = super(ItemDetailView, request).get_context_data() <---------------- error from this line
context["comments"] = Comment.objects.filter(item_id=id, status='True')
return context
here is the add coment view
def addcomment(request,id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.item_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
Here is the traceback
Traceback (most recent call last):
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\detail.py", line 107, in get
context = self.get_context_data(object=self.object)
File "C:\Users\Ahmed\Desktop\Project 4.3\core\views.py", line 113, in get_context_data
context["comments"] = Comment.objects.filter(item_id=id, status='True')
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1315, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
The signature of get_context_data(...) method is wrong in your view. It should be as follows,
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["comments"] = Comment.objects.filter(item=self.object, status='True')
return context

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 unique constraint not working

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.

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.