I am using autocomplete-light to suggest names in a form field. It is go well in the createView ,but when I want to change a value in the very same field it tlod me "invalid literal for int() with base 10:" error.
I鈥檝 been read all the related issues and did not have a clue.Can some one help me.


#forms.py
class CaoZuoPiaoForm_zhengling(forms.ModelForm):
yunweizhan = forms.ModelChoiceField(YunWeiZhan.objects.all())
nipiaoren=forms.ModelChoiceField(queryset=UserProfile.objects.all(),widget=autocomplete.ModelSelect2(url='bdgqpt:name-autocomplete'))
shenpiaoren=forms.ModelChoiceField(queryset=UserProfile.objects.all(),widget=autocomplete.ModelSelect2(url='bdgqpt:name-autocomplete'))
caozuoren=forms.ModelChoiceField(queryset=UserProfile.objects.all(),widget=autocomplete.ModelSelect2(url='bdgqpt:name-autocomplete'))
jianhuren=forms.ModelChoiceField(queryset=UserProfile.objects.all(),widget=autocomplete.ModelSelect2(url='bdgqpt:name-autocomplete'))
zhibanfuzeren=forms.ModelChoiceField(queryset=UserProfile.objects.all(),widget=autocomplete.ModelSelect2(url='bdgqpt:name-autocomplete'))
falinshijian = forms.DateTimeField(widget=DateTimeWidget(usel10n=True,bootstrap_version=3,
options=dateTimeOptions,attrs=dateTimeAtts),required=False)
kaishishijian=forms.DateTimeField(widget=DateTimeWidget(usel10n=True,bootstrap_version=3,
options=dateTimeOptions,attrs=dateTimeAtts),required=False)
jiesushijian=forms.DateTimeField(widget=DateTimeWidget(usel10n=True,bootstrap_version=3,
options=dateTimeOptions,attrs=dateTimeAtts),required=False)
class Meta:
model = CaoZuoPiao
fields = "__all__"
def __init__(self, *args, **kwargs):
super(CaoZuoPiaoForm_zhengling, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-4'
self.helper.field_class = 'col-md-8'
self.helper.layout=Layout(
'yunweizhan',
'biandiansuo',
'leibie',
'bianhao',
'caozuoneirong',
'nipiaoren',
'shenpiaoren',
'falinren',
'falinshijian',
'kaishishijian',
'jiesushijian',
'caozuoren',
'jianhuren',
'zhibanfuzeren',
'bushu',
'zhuangtai',
ButtonHolder(Submit('submit','Submit')),
)
#views.py
def caozuopiao_update(request, id=None):
if not request.user.is_authenticated():
return render(request, 'bdgqpt/login.html')
else:
instance = get_object_or_404(CaoZuoPiao, id=id)
form = CaoZuoPiaoForm_zhengling(request.POST or None,instance=instance)
title="Modify"
if form.is_valid():
instance.save()
messages.success(request,"Success")
return redirect('bdgqpt:caozuopiaohomepage')
context = {
"form": form,
"title":title,
}
return render(request, 'bdgqpt/caozuopiao/caozuopiao_update_form.html', context)
caozuopiao_update_form.html
{% extends 'bdgqpt/base.html' %}
{% load crispy_forms_tags %}
{% block title %}{{title}}|{{block.super}}{% endblock %}
{% block liangpiao_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6 col-sm-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<h3>{{title}}</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
{{form.as_p}}
</div>
</div>
</div>
{% endblock body %}
Could you isolate and reproduce this in a minimal app in the test_project ?
There's a bit too much info here
Thanks for your report !
Thanks for your replay.I think I may found the reason but I don't know how to fix it.
This is the data return form my class NameAutocomplete(autocomplete.Select2QuerySetView)
{"results": [{"text": sunny, "id": 2}, {"text": test, "id": 3}], "pagination": {"more": false}}
In the create object view it saves the "text"(like, sunny or test) into the database, but when in edit view it go for a "id" ('sunny' not equals '2' literally),so they don't match. If I manually change the field value equals to "id" it works as expected.
I have tried using this,
class NameAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = UserProfile.objects.all()
if self.q:
qs = qs.filter(full_name__icontains=self.q)
return qs
def get_result_value(self, result):
"""Return the value of a result."""
return result.pk
but it did not workout.
I need your help, thank you.
Could you please try to reproduce your case in a new, empty app in the test_project ? You can fork this repo and add your app to test_project.
Thanks !
Would you happen to be using a ModelChoiceField with a ModelSelect2Multiple instead of a ModelSelect2 or a ModelMultipleChoiceField with a ModelSelect2 instead of a ModelSelect2Multiple ?
Thanks for your replay. I have checked my forms and I was using ModelChoiceField with a ModelSelect2 Widget ,I think it was right.
I have fork your repo and uploaded my test_project,would please take a look at it, thank you. You may need to create a superuser or use "admin:admin123" to login. The url you need is http://127.0.0.1:8000/bdgqpt/caozuopiao/ , the test_project is bdgqpt_test: https://github.com/sunqy1212/django-autocomplete-light/tree/master/test_project/bdgqpt_test
Hi, I have solve the promble. Only need to change one line:
`in dal/widgets.py
class QuerySetSelectMixin(WidgetMixin):
"""QuerySet support for choices."""
def filter_choices_to_render(self, selected_choices):
"""Filter out un-selected choices if choices is a QuerySet."""
self.choices.queryset = self.choices.queryset.filter(
#pk__in=[c for c in selected_choices if c] #change this line as following
FIELD__in=[c for c in selected_choices if c]
)
# "FIELD" is the field using the autocomplete widget rather than "pk" `
I think it is batter to pass the FIELD as a parameter.
I don't understand, your model field is:
nipiaoren = models.CharField(max_length=10)
But your form field is:
nipiaoren=forms.ModelChoiceField(queryset=UserProfile.objects.all(),widget=autocomplete.ModelSelect2(url='bdgqpt:name-autocomplete'))
You should use ModelChoiceField/ModelSelect2 for ForeignKey, not for CharField, unless you really know what you're doing.
CharField may contain any string, ModelChoiceField expects an integer value. So that's why your CharField may crash your ModelChoiceField by providing a value that doesn't cast to integer.
Hi,
It鈥榮 been a while ,finally I find the solution by not change the dal/widgets.py. The problem is the model, it only need to declare the filed as PK, and everything went well.
class UserProfile(models.Model):
user = models.OneToOneField(User)
ID_No = models.CharField(max_length=8)
full_name = models.CharField(max_length=10, primary_key=True)
phone_number = models.CharField(max_length=11)
def __str__(self):
return self.full_name
class Meta:
verbose_name = 'UserProfile'
verbose_name_plural = 'UserProfile'
Thank you for your help, good luck.
NP, njoy
:guitar:
I am facing the same issue... But, I dont think that would be correct add "primary_key=True" in my case. Adding this option, it works properly, but its not make sense to add primary_key in a text field. Have some other alternative?
Use the right form field class please.
Hi jpic,
in my form.py:
class OcuForm(forms.ModelForm):
titulo = forms.ModelChoiceField(
queryset=Ocu.objects.all(),
widget=autocomplete.ModelSelect2(url='ocu-autocomplete')
)
class Meta:
model = Ocu
fields = ('__all__')
# fields = ('titulo', )
model.py
class Ocu(models.Model):
titulo = models.CharField(max_length=200)
def __str__(self):
return self.titulo
How would you suggest?
Changing to:
titulo = forms.ModelChoiceField(
queryset=Ocupacao.objects.all(),
widget=autocomplete.Select2(url='ocu-autocomplete')
)
I get encode error:
(...)
File "/usr/local/lib/python2.7/dist-packages/django/forms/boundfield.py", line 127, in as_widget
**kwargs
File "/usr/local/lib/python2.7/dist-packages/dal/widgets.py", line 150, in render
widget = super(WidgetMixin, self).render(name, value, attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py", line 220, in render
context = self.get_context(name, value, attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py", line 663, in get_context
context = super(Select, self).get_context(name, value, attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py", line 625, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "/usr/local/lib/python2.7/dist-packages/dal/widgets.py", line 140, in optgroups
self.filter_choices_to_render(selected_choices)
File "/usr/local/lib/python2.7/dist-packages/dal/widgets.py", line 70, in filter_choices_to_render
self.choices = [c for c in self.choices if
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1123, in __iter__
yield self.choice(obj)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1129, in choice
return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1194, in label_from_instance
return force_text(obj)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py", line 80, in force_text
s = six.text_type(bytes(s), encoding, errors)
@thobryan
Try this:
forms.py:
from dal.widgets import QuerySetSelectMixin
class OcuForm(QuerySetSelectMixin,forms.ModelForm):
titulo = forms.ModelChoiceField(
queryset=Ocu.objects.all(),
widget=autocomplete.ModelSelect2(url='ocu-autocomplete')
)
class Meta:
model = Ocu
#fields = ('__all__')
fields = ('titulo', )
def filter_choices_to_render(self, selected_choices):
"""Filter out un-selected choices if choices is a QuerySet."""
self.choices.queryset = self.choices.queryset.filter(
titulo__in=[c for c in selected_choices if c]
)
Hi sunqy1212,
With this change I get the following error:
File "/usr/local/lib/python2.7/dist-packages/dal/widgets.py", line 150, in render
widget = super(WidgetMixin, self).render(name, value, attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py", line 220, in render
context = self.get_context(name, value, attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py", line 663, in get_context
context = super(Select, self).get_context(name, value, attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py", line 625, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "/usr/local/lib/python2.7/dist-packages/dal/widgets.py", line 140, in optgroups
self.filter_choices_to_render(selected_choices)
File "/usr/local/lib/python2.7/dist-packages/dal/widgets.py", line 183, in filter_choices_to_render
pk__in=[c for c in selected_choices if c]
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 784, in filter
return self._filter_or_exclude(False, args, *kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 802, in _filter_or_exclude
clone.query.add_q(Q(args, *kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1261, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1287, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1221, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1115, in build_lookup
return final_lookup(lhs, rhs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/lookups.py", line 219, in get_prep_lookup
rhs_value = self.lhs.output_field.get_prep_value(rhs_value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'EMPREGADA DOMxc9STICA
Would you like the table dump?
No need for table dump. I don't think the ModelChoiceField is meant to work with non primary keys at all. Perhaps you can try a ChoiceField instead ?
Hi jpic,
With the following code:
from dal.widgets import QuerySetSelectMixin
class OcuForm(QuerySetSelectMixin,forms.ModelForm):
titulo = forms.ChoiceField(
queryset=Ocu.objects.all(),
widget=autocomplete.ModelSelect2(url='ocu-autocomplete')
)
class Meta:
model = Ocu
#fields = ('__all__')
fields = ('titulo', )
def filter_choices_to_render(self, selected_choices):
"""Filter out un-selected choices if choices is a QuerySet."""
self.choices.queryset = self.choices.queryset.filter(
titulo__in=[c for c in selected_choices if c]
)
I get the following error:
Unhandled exception in thread started by
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper
fn(args, *kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(_exception)
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper
fn(args, *kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 116, in populate
app_config.ready()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/local/lib/python2.7/dist-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/srv/www/Emp.com.br/application/Emp/oportunidade/admin.py", line 11, inkwargs
from ocupacao.forms import OcupacaoForm
File "/srv/www/Emp.com.br/application/Emp/ocupacao/forms.py", line 6, in
class OcupacaoForm(QuerySetSelectMixin,forms.ModelForm):
File "/srv/www/Emp.com.br/application/Emp/ocupacao/forms.py", line 9, in OcupacaoForm
widget=autocomplete.ModelSelect2(url='ocupacao-autocomplete')
File "/usr/local/lib/python2.7/dist-packages/django/forms/fields.py", line 778, in __init__
help_text=help_text, *args, *
TypeError: __init__() got an unexpected keyword argument 'queryset'
Most helpful comment
I don't understand, your model field is:
But your form field is:
You should use ModelChoiceField/ModelSelect2 for ForeignKey, not for CharField, unless you really know what you're doing.
CharField may contain any string, ModelChoiceField expects an integer value. So that's why your CharField may crash your ModelChoiceField by providing a value that doesn't cast to integer.