我有一个名为record的模型,但它需要一个外键(条形码),我不想在表单中添加一个select(默认情况下django的方式),而不是我要插入的它是手动的,所以我在 forms.py
中完成了这项工作class add_record_form(forms.ModelForm):
barcode = forms.CharField()
class Meta:
model = Record
exclude = ('product',)
但我不知道如何将值传递给我的视图并将其添加到记录表中。我收到错误“Record.barcode必须是条形码的实例”
当我获得条形码实例时,我不得不在视图中添加与该条形码相关联的产品,这就是我在表单中排除产品字段的原因。
views.py
def add_barcode_view(request):
if request.method == 'POST':
formu = add_record_form(request.POST)
if formu.is_valid():
bcode = formu.cleaned_data['barcode']
prod = Producto.objects.get(barcode=bcode)
cant = formu.cleaned_data['amount']
aux = prod.amount - cant
add = formu.save(commit = False)
if (aux >= 0):
prod.amount= aux
prod.save()
add.save()
return HttpResponseRedirect('/record/%s' %add.id)
else:
formu = add_record_form(instance = add)
mensaje = "amount not available"
ctx = {'men':mensaje, 'form': formu}
return render_to_response('inventario/add_record.html', ctx, context_instance = RequestContext(request))
else:
formu = add_record_form()
ctx = {'form': formu}
return render_to_response('inventario/add_record.html', ctx , context_instance = RequestContext(request))
记录模型和条形码 我想在添加记录表格中手动插入条形码代码
class Barcode(models.Model):
code = models.CharField(max_length=13, unique = True)
date = models.DateField(auto_now = True)
def __unicode__(self):
return self.code
class Record(models.Model):
barcode = models.ForeignKey(Barcode)
record_date = models.DateField(auto_now = True)
producto = models.ForeignKey(Producto)
amount = models.IntegerField()
description = models.TextField(max_length=150)
追溯
Environment:
Request Method: POST
Request URL: http://localhost:8000/add/record/
Django Version: 1.5.3
Python Version: 2.7.9
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'sif.apps.home',
'sif.apps.inventario',
'sif.apps.web_services.ws_producto',
'rest_framework')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "D:\MIS DOCUMENTOS\Documents\GitHub\proyecto_formativo\sif\sif\apps\inventario\views.py" in add_record_view
156. if formu.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
126. return self.is_bound and not bool(self.errors)
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _get_errors
117. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
274. self._post_clean()
File "C:\Python27\lib\site-packages\django\forms\models.py" in _post_clean
315. self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "C:\Python27\lib\site-packages\django\forms\models.py" in construct_instance
52. f.save_form_data(instance, cleaned_data[f.name])
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
466. setattr(instance, self.name, data)
File "C:\Python27\lib\site-packages\django\db\models\fields\related.py" in __set__
405. self.field.name, self.field.rel.to._meta.object_name))
Exception Type: ValueError at /add/record/
Exception Value: Cannot assign "u'144253491444'": "Record.barcode" must be a "Barcode" instance.
答案 0 :(得分:0)
简单的代码如下:
if form.is_valid():
record = form.save(commit=False)
record.barcode = barcode
record.save()
使用save
的表单的commiit=False
方法不会在模型对象上触发save
,这样您就可以检索准备保存对象,为其指定字段或更改某些内容之后保存。
当然,在上面的例子中,条形码应该是Barcode
实例。
答案 1 :(得分:0)
首先,您的命名不正确。请遵循PEP8规则并对变量,类名,所有内容使用英语单词。请将formu
更改为form
,将Producto
更改为Product
,将add_record_form
更改为AddRecordForm
或RecordForm
。
问题是您正在使用字符串而不是实际的Barcode
对象进行数据库查找。另一个问题是,在创建记录之前,您没有指定如何获得正确的Product
实例,因此无论何时创建新条形码,我都会创建产品。
您应该按如下方式更新您的查看功能:
def add_barcode_view(request):
...
if formu.is_valid():
barcode, created = Barcode.objects.get_or_create(
code=formu.cleaned_data['barcode']
)
add = formu.save(commit=False)
add.barcode = barcode
prod, created = Producto.objects.get_or_create(barcode=barcode)
add.producto = prod
...
...
答案 2 :(得分:0)
您需要覆盖 clean
中的 add_record_form
以避免出现如下错误:
def clean(self):
barcode = Barcode.objects.get(id=self.cleaned_data.get("barcode"))
return {'barcode': barcode}