Question

I've been poking at this for a few hours and I feel tunneled on this problem. This view should do two operations. The fist and working operation is creating the object with the submitted form data. The second operation is updating the 'status' field based on the unique field 'bar_code'. After initially saving, then updating I get the error that is caused by the unique attribute "%s with this %s already exists.", which is expected. I'd really like to keep the view to perform both of these operations.

def check_in_part_two(request):
    errlst=[]
    c={}
    c.update(csrf(request))
    if request.method == 'POST':
        form = PartForm(request.POST)
        if form.is_valid():
            try:
                # Test if the part row exists based on bar_code
                instance = Part.objects.get(bar_code=request.POST['bar_code'])
            except Part.DoesNotExist:
                # Clean the sn and create new row
                form.cleaned_data['serial_number']
                form.save()
                return http.HttpResponseRedirect('/current_count/')
            else:
                edit = PartForm(request.POST, instance=instance, fields=['status'])
                if edit.is_valid():
                    edit.cleaned_data['bar_code']
                    edit.save()
                    return http.HttpResponseRedirect('/current_count/')

    else:
        form = PartForm(initial={'status':3L, 'serial_number':'placeholder'})
    return render(request,'add_part.html',{
                                           'title':'Add Item',
                                           'form': form,
                                           })
Was it helpful?

Solution

First, I don't know what you're doing with the form.cleaned_data['serial_number'] and edit.cleaned_data['bar_code'] lines. Those are keys in a dict, not methods, so just having them on their own on a line does nothing.

Second, you're making this too complicated. The following code is functionally equivalent, and probably more functional at that:

def check_in_part_two(request):
    if request.method == 'POST':
        try:
            part = Part.objects.get(bar_code=request.POST.get('bar_code'))
        except Part.DoesNotExist:
            form = PartForm(request.POST)
        else:
            form = PartForm(request.POST, instance=part)

        if form.is_valid():
            form.save()
            return http.HttpResponseRedirect('/current_count/')

    else:
        form = PartForm(initial={'status':3L, 'serial_number':'placeholder'})

    return render(request, 'add_part.html', {
        'title':'Add Item',
        'form': form,
    })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top