简体   繁体   中英

Python 3 / Django 2, Passing a dictionary value to form field before saving

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:

  • Dictionary is two columns, 'Product Code', and 'Product'
  • The first three digits of the Serial number entered on the form will match to the Product Code in the dictionary.
  • Once the user submits the form, I want it to evaluate the serial number's first three digits, compare it to the dictionary keys, then change the 'product' form field to the dict['Product'] before saving the form.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM