Python 3 / Django 2,在保存之前将字典值传递给表单字段

时间:2018-01-05 18:18:28

标签: python django forms

我正在尝试让我的应用使用在表单上输入的序列号,与字典进行比较并在保存之前更新表单上的产品字段。这是详细信息:

  • 字典是两列,“产品代码”和“产品”
  • 表单上输入的序列号的前三位数字将与字典中的“产品代码”匹配。
  • 一旦用户提交表单,我希望它评估序列号的前三位数字,将其与字典键进行比较,然后在保存表单之前将“product”表单字段更改为dict ['Product']。

以下是我的观点:

def create(request):
#Page with input form to submit new records
if request.method == 'POST':
    form = RecordForm(request.POST)
    if form.is_valid():
        sn = request.POST.get('serial')
        with open('prodlist.csv') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                if sn[0:2] in row['Product Code']:
                    form.fields['product'].update = row['Product']
                else:
                    pass
        form.save()
        return HttpResponseRedirect('/tracker/all/')
else:
    form = RecordForm()
return render(request, 'tracker/form2.html', {'form': form}, RequestContext(request))

有了这个,我正在为'产品'作出一个关键错误。有没有办法在提交后将值传递给表单字段?

更新

我在forms.py:

中将产品字段添加到表单本身
class RecordForm(ModelForm):
class Meta:
    model = Record
    fields = ['serial',
              'ticket',
              'product',
              'eng_date',
              'customer',
              'details',
              'owner',
              'status',
              'seed_num'
             ]
    widgets = {
            'eng_date': DateInput(),
            }

我已将form.fields['product'].update = row['Product']行更改为form.cleaned_data['product'] = row['Product']。并添加了一个else:子句来编写一些东西,以防它找不到序列:else: form.cleaned_data['product'] = '5678'

以下是完整视图:

def create(request):
#Page with input form to submit new records
if request.method == 'POST':
    form = RecordForm(request.POST)
    if form.is_valid():
        sn = request.POST.get('serial')
        with open('prodlist.csv') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                if sn[0:2] in row['Product Code']:
                    form.cleaned_data['product'] = row['Product']
                else:
                    form.cleaned_data['product'] = '5678'
        form.save()
        return HttpResponseRedirect('/tracker/all/')
else:
    form = RecordForm()
return render(request, 'tracker/form2.html', {'form': form}, RequestContext(request))

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:0)

尝试这样做

form.cleaned_data['product'] = row['Product']

答案 1 :(得分:0)

我能够让它运转起来!必须使用obj = form.save(commit=false),然后将值传递给obj.product,然后传递给obj.save()。以下是现有的观点:

def create(request):
#Page with input form to submit new records
if request.method == 'POST':
    form = RecordForm(request.POST)
    if form.is_valid():
        sn = request.POST.get('serial')
        with open('prodlist.csv') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                if sn[0:2] in row['Product Code']:
                    obj = form.save(commit=False)
                    obj.product = row['Product']
                    obj.save()
                    break
                else:
                    pass
        form.save()
        return HttpResponseRedirect('/tracker/all/')
else:
    form = RecordForm()
return render(request, 'tracker/form2.html', {'form': form}, RequestContext(request))