我正试图用Django的表单更新数据库中的一个现有行。我创建新行没有问题,但当我尝试更新现有行时,我会得到一个ValueError(在文章末尾进行回溯(。
我知道我的"product"属性被误认为主键,但就是不明白为什么。这是我的代码:
型号.py
class Rates(models.Model):
my_id = models.AutoField(primary_key=True)
product = models.CharField(unique=True, max_length=255)
taux_comm_1 = models.FloatField(blank=True, null=True)
taux_comm_2 = models.FloatField(blank=True, null=True)
taux_euros = models.FloatField(blank=True, null=True)
taux_uc = models.FloatField(blank=True, null=True)
taux_prud = models.FloatField(blank=True, null=True)
表单.py
class RatesForm(forms.ModelForm):
class Meta:
model = Rates
fields = ['product', 'taux_comm_1', 'taux_comm_2', 'taux_euros', 'taux_uc', 'taux_prud']
labels = {
'product': "Nom du produit",
'taux_comm_1': "Taux de commission de production",
'taux_comm_2': "Taux de commission de portefeuille",
'taux_euros': "Taux de commission sur l'encours euros",
'taux_uc': "Taux de commission sur l'encours UC",
'taux_prud': "Taux de commission sur l'encours UC Prudentes",
}
def __init__(self, *args, **kwargs):
super(RatesForm, self).__init__(*args, **kwargs)
self.fields['product'].widget.attrs.update({'class': 'form-control', 'readonly':'readonly'})
self.fields['taux_comm_1'].widget.attrs.update({'class': 'form-control'})
self.fields['taux_comm_2'].widget.attrs.update({'class': 'form-control'})
self.fields['taux_euros'].widget.attrs.update({'class': 'form-control'})
self.fields['taux_uc'].widget.attrs.update({'class': 'form-control'})
self.fields['taux_prud'].widget.attrs.update({'class': 'form-control'})
视图.py
product = request.session['product']
if request.method == 'POST':
rates_form = RatesForm(request.POST)
if rates_form.is_valid():
rate = Rates.objects.get(pk=2)
rates_form = RatesForm(instance=rate)
rates_form.cleaned_data.get('product')
rates_form.cleaned_data.get('taux_comm_1')
rates_form.cleaned_data.get('taux_comm_2')
rates_form.cleaned_data.get('taux_euros')
rates_form.cleaned_data.get('taux_uc')
rates_form.cleaned_data.get('taux_prud')
rates_form.save()
return redirect('/accountancy/rates/')
else:
search_form = SearchProduct()
rate = Rates.objects.get(pk=2)
rates_form = RatesForm(instance=rate, initial={'product': product})
回溯
Traceback (most recent call last):
File "/home/<3/.local/lib/python3.5/site-
packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/<3/.local/lib/python3.5/site-
packages/django/core/handlers/base.py", line 128, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "/home/<3/.local/lib/python3.5/site-
packages/django/core/handlers/base.py", line 126, in
_get_response
response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "/home/<3/.local/lib/python3.5/site-
packages/django/contrib/auth/decorators.py", line 21, in
_wrapped_view
return view_func(request, *args, **kwargs)
File "/home/<3/vsc-workspace/ola/ola/accountancy/views.py", line
109, in view_update_rate
'update': update,
File "/home/<3/.local/lib/python3.5/site-
packages/django/shortcuts.py", line 36, in render
content = loader.render_to_string(template_name, context,
request,
using=using)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/base.py", line 175, in render
return self._render(context)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/base.py", line 943, in render
bit = node.render_annotated(context)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/base.py", line 910, in render_annotated
return self.render(context)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/base.py", line 910, in render_annotated
return self.render(context)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/base.py", line 999, in render
return render_value_in_context(output, context)
File "/home/<3/.local/lib/python3.5/site-
packages/django/template/base.py", line 978, in
render_value_in_context
value = str(value)
File "/home/<3/.local/lib/python3.5/site-
packages/django/utils/html.py", line 380, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "/home/<3/.local/lib/python3.5/site-
packages/django/forms/boundfield.py", line 36, in __str__
return self.as_widget()
File "/home/<3/.local/lib/python3.5/site-
packages/django/forms/boundfield.py", line 118, in as_widget
**kwargs
File "/usr/local/lib/python3.5/dist-
packages/smart_selects/widgets.py", line 125, in render
available_choices = self._get_available_choices(self.queryset,
value)
File "/usr/local/lib/python3.5/dist-
packages/smart_selects/widgets.py", line 161, in
_get_available_choices
item = queryset.filter(pk=value).first()
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/query.py", line 854, in
_filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/sql/query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/sql/query.py", line 1277, in _add_q
split_subq=split_subq,
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/sql/query.py", line 1215, in
build_filter
condition = self.build_lookup(lookups, col, value)
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/sql/query.py", line 1085, in
build_lookup
lookup = lookup_class(lhs, rhs)
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/lookups.py", line 18, in __init__
self.rhs = self.get_prep_lookup()
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/lookups.py", line 68, in
get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/home/<3/.local/lib/python3.5/site-
packages/django/db/models/fields/__init__.py", line 947, in
get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'Product A'
Django Traceback
__class__ <class 'django.db.models.fields.AutoField'>
self <django.db.models.fields.AutoField: id>
value 'Product A'
如果你知道我如何解决那个问题,我将非常感谢你的帮助。
您似乎在会话中保存了文本值"产品A",而不是产品的实际ID。如果无法更改保存的内容,则需要基于该名称获取产品实例。
但在你看来,你也在做一些非常奇怪的事情。您不应该重新实例化表单,并且所有这些cleaned_data
行完全不起任何作用。此外,要小心压痕;else
指的是第一个if
而不是第二个。
product = Product.objects.get(product_name=request.session['product']) # or whatever the name field is
rate = Rates.objects.get(pk=2)
if request.method == 'POST':
rates_form = RatesForm(request.POST, instance=rate)
if rates_form.is_valid():
rates_form.save()
return redirect('/accountancy/rates/')
else:
search_form = SearchProduct()
rates_form = RatesForm(instance=rate, initial={'product': product})
return render(...)