I'm trying to get my app to use a serial number, entered on a form, to compare to a dictionary and update a product field on a form before saving. Here's the details:
Here is my view:
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))
With this, I'm geting a key error for the 'product' piece. Is there a way to pass a value to a form field after it is submitted?
Update:
I've added the product field to the form itself in 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(),
}
And I've changed the form.fields['product'].update = row['Product']
line to form.cleaned_data['product'] = row['Product']
. and added an else: clause to write something anyway, in case it doesn't find the serial: else: form.cleaned_data['product'] = '5678'
Here's the full view:
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))
Any help would be greatly appreciated :)
试试这个
form.cleaned_data['product'] = row['Product']
I was able to get it working! Had to use obj = form.save(commit=false)
, then pass the value to that as obj.product
, and then ust obj.save()
. Here is the view as it stands:
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.