In short, I have been having a hard time getting a ModelFormSet to
save. The formset is created from a queryset, and it's only intended
to edit one field of existing objects.

After a long string of mistakes and fixes, I'm finally stumped. The
following bit of code produces a TypeError exception about converting
a float to a decimal, but in my forms I'm not editing float or decimal
fields...only one CharField:

Code:

if request.method == 'POST':
    formset = RetainStatusFormSet(request.POST, request.FILES,)
    if formset.is_valid():
        try:
            instances = formset.save()
        except Exception, err:
            print type(err)
            print err.message

###

Exception:

<type 'exceptions.TypeError'>
Cannot convert float to Decimal.  First convert the float to a string

###

I will paste my code here, as much as I think is relevant, with the
most relevant code on top. As you can see in the request.POST that I
paste at the very end, there are only the usual management form
values, one string value per form, and one ID value per form being
passed. I have not a clue where this TypeError is coming from.

###

def newsession(request):
    RetainStatusFormSet = modelformset_factory(Retain,
                                               RetainStatusChangeForm,
                                               exclude=('retain',
                                                        'date',
                                                        'lot',
                                                        'sub_lot',
                                                        'amount',
                                                        'notes',
 
'content_type',
                                                        'object_id',
                                                        'product'),
                                              extra=0)

    if request.method == 'POST':
        formset = RetainStatusFormSet(request.POST, request.FILES,)
        if formset.is_valid():
            try:
                instances = formset.save()
            except Exception, err:
                print type(err)
                print err.message
            return HttpResponseRedirect('/qc/newsession')
    else:
        formset = RetainStatusFormSet(queryset=
                                      Retain.objects.select_related
().filter(status='Pending'))

    return render_to_response('qc/newsession.html',
                              {'formset': formset,},
                              context_instance= RequestContext
(request))

class RetainStatusChangeForm(forms.ModelForm):
    """
    A form to select a status for a retain.
    """

    status = forms.ChoiceField(widget=RetainStatusChangeWidget,
                                   choices=([
                                       ['Passed',''],
                                       ['Rejected',''],
                                       ['Resample',''],
                                       ['Hold',''],
                                       ['Pending','']
                                   ]),
                                   initial='Passed'
                                  )
    class Meta:
        model = Retain
        fields = ['status']

class RetainStatusChangeRenderer(widgets.RadioFieldRenderer):
    def render(self):
        """Outputs table cells for this set of radio fields."""
        return mark_safe(u'%s' % u'\n'.join([u'<td
class="qcradiobutton">%s</td>'
                % force_unicode(w) for w in self]))

class RetainStatusChangeWidget(widgets.RadioSelect):
    renderer = RetainStatusChangeRenderer

class Retain(models.Model):
    """
    Data related to the retained sample of a production lot.
    """
    retain = models.PositiveSmallIntegerField()
    date = models.DateField("Date on which product was QCed")
    lot = models.PositiveIntegerField()
    sub_lot = models.PositiveSmallIntegerField(blank=True, null=True)
    status = models.CharField(max_length=25)
    amount = models.DecimalField(max_digits=6,
                                 decimal_places=2,
                                 blank=True, null=True)
    notes = models.TextField(blank=True, null=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    product = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        ordering = ['-date', '-retain']

###############
# and the template
###############

<form method="POST" action="/qc/newsession/">
{{ formset.management_form }}

<table class="sortable">
<tr>
    <th class="qcheaders">Retain</th>
    <th class="qcheaders">Number</th>
    <th class="qcheaders">Lot</th>
    <th class="qcheaders">Amount</th>
    <th class="qcheaders">Reference</th>
    <th class="qcheaders" "sorttable_nosort">Passed</th>
    <th class="qcheaders" "sorttable_nosort">Rejected</th>
    <th class="qcheaders" "sorttable_nosort">Resample</th>
    <th class="qcheaders" "sorttable_nosort">Hold</th>
    <th class="qcheaders" "sorttable_nosort">Pending</th>
</tr>
{% for form in formset.forms %}
<tr>
    <td class="qcbody"><a href="/flavorbase/
{{ form.instance.product.id }}">{{ form.instance.retain }}</a></td>
    <td class="qcbody">{{ form.instance.product.number }}</td>
    <td class="qcbody">{{ form.instance.amount }}</td>
    <td class="qcbody">{{ form.instance.lot }}</td>
    <td class="qcbody">{{ form.instance.product.retains.all.1 }}</td>
    <!--
        This variable will output cells for all the radio buttons.
        They have the class "qcradiobutton" and contain nothing but a form
element.
    -->
    {{ form }}
</tr>
{% endfor %}
</table>

<p><input type="submit" value="Update Statuses" /></p>

</form>

##################################################
# I get the following if I print request.POST after a submission
#formatted for readability

<QueryDict: {
u'form-1-id': [u'10723'],
u'form-TOTAL_FORMS': [u'3'],
u'form-0-status': [u'Resample'],
u'form-2-id': [u'10722'],
u'form-0-id': [u'10724'],
u'form-1-status': [u'Rejected'],
u'form-INITIAL_FORMS': [u'3'],
u'csrfmiddlewaretoken': [u'###########'],
 u'form-2-status': [u'Passed']}>

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=.


Reply via email to