Re: Testing formset validation

2010-10-08 Thread ses1984
I should also add that neither the formset nor the form report .errors
or .non_form_errors() at all.

On Oct 8, 6:15 pm, ses1984 <ses1...@gmail.com> wrote:
> I have a pretty simple form, defined below, that I am setting
> according to some initial data, and no matter what I try, I can't seem
> to get it to validate in a test.
>
> I have created some test data, which is an array with one dictionary
> element, where the dictionary corresponds to the form. If I create a
> singular from from the dictionary element, it is valid, but if I
> create a formset from the list which contains only that very same
> dictionary, it's not valid.
>
> ###
>
> class FormulaRow(forms.Form):
>     ingredient_number = forms.CharField(label="")
>     amount = forms.DecimalField(label="", max_digits=9,
> decimal_places=5)
>
> ###
>
> >>> initial = [{'amount': '1000.000', 'ingredient_number': '100'}]
> >>> initial_singular= initial[0]
> >>> form = FormulaRow(initial_singular)
> >>> form.is_valid()
> True
> >>> FormulaFormSet = formset_factory(FormulaRow)
> >>> formset = FormulaFormSet(initial=initial)
> >>> formset.is_valid()
>
> False

-- 
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=en.



Testing formset validation

2010-10-08 Thread ses1984
I have a pretty simple form, defined below, that I am setting
according to some initial data, and no matter what I try, I can't seem
to get it to validate in a test.

I have created some test data, which is an array with one dictionary
element, where the dictionary corresponds to the form. If I create a
singular from from the dictionary element, it is valid, but if I
create a formset from the list which contains only that very same
dictionary, it's not valid.

###

class FormulaRow(forms.Form):
ingredient_number = forms.CharField(label="")
amount = forms.DecimalField(label="", max_digits=9,
decimal_places=5)

###

>>> initial = [{'amount': '1000.000', 'ingredient_number': '100'}]
>>> initial_singular= initial[0]
>>> form = FormulaRow(initial_singular)
>>> form.is_valid()
True
>>> FormulaFormSet = formset_factory(FormulaRow)
>>> formset = FormulaFormSet(initial=initial)
>>> formset.is_valid()
False

-- 
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=en.



Re: View to edit many-to-many relationship with extra fields

2010-10-02 Thread ses1984
Actually, I have added on to what I started with significantly, and
what I ended up doing was emulating formsets with javascript on the
page. When the page POSTs, I can get cleaned formset data from the
request.

On Oct 2, 8:11 am, Felix Dreissig <f...@f30.me> wrote:
> I'm not at all sure that this might help youm, so sorry if I write BS...
>
> Can't you just use form prefixes to kepp the form namespaces 
> seperated?http://docs.djangoproject.com/en/1.2/ref/forms/api/#prefixes-for-forms
>
> Regards,
> Felix
>
> On 01.10.2010 22:22, ses1984 wrote:
>
>
>
> >http://docs.djangoproject.com/en/1.2/topics/db/models/#extra-fields-o...
>
> > I have two models with a many-to-many relationship through another
> > table with extra fields. In this case, I have one extra field which
> > represents the weight of the relationship.
>
> > I'm working on a view to edit the relationships between the two
> > models. If we call the two models left-hand-side and right-hand-side,
> > then the view is specific to one instance of the LHS, and the purpose
> > of the view is to add relationships from that LHS-row to an arbitrary
> > number of pre-existing RHS-rows.
>
> > Writing a view that, given an instance of the LHS, adds a single
> > weighted relationship to an element on the RHS is pretty trivial.
> > Writing  view that adds an arbitrary number of relationships to the
> > RHS is not that trivial, and that's what I would like to deliver to my
> > users.
>
> > So far the view for a particular LHS-instance renders a page with a
> > form to define a single additional relationship to the RHS. I have
> > included a basic ajax function that GETs another form to the page.
> > This is where the problem comes up: IDs of the form elements are going
> > to overlap, and I won't be able to handle this when the form is
> > POSTed.
>
> > I have thought of two options I could try to tackle this so far, both
> > with javascript. The first would be to increment an index and send
> > that through the ajax function to the view that returns a new form.
> > The second would be to hook into the POST submission and munge the
> > data before it's passed back to django to save model instances.
>
> > It seems to me that something like this, while not common, has to have
> > been done before in web apps. I was wondering if there were some
> > established patterns to do this sort of thing, and if I am on the
> > right track. I have searched a few places including django snippets
> > and packages to see if something like this has been done before, but I
> > couldn't find anything. I'm not sure if I'm using the best search
> > terms.

-- 
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=en.



View to edit many-to-many relationship with extra fields

2010-10-01 Thread ses1984
http://docs.djangoproject.com/en/1.2/topics/db/models/#extra-fields-on-many-to-many-relationships

I have two models with a many-to-many relationship through another
table with extra fields. In this case, I have one extra field which
represents the weight of the relationship.

I'm working on a view to edit the relationships between the two
models. If we call the two models left-hand-side and right-hand-side,
then the view is specific to one instance of the LHS, and the purpose
of the view is to add relationships from that LHS-row to an arbitrary
number of pre-existing RHS-rows.

Writing a view that, given an instance of the LHS, adds a single
weighted relationship to an element on the RHS is pretty trivial.
Writing  view that adds an arbitrary number of relationships to the
RHS is not that trivial, and that's what I would like to deliver to my
users.

So far the view for a particular LHS-instance renders a page with a
form to define a single additional relationship to the RHS. I have
included a basic ajax function that GETs another form to the page.
This is where the problem comes up: IDs of the form elements are going
to overlap, and I won't be able to handle this when the form is
POSTed.

I have thought of two options I could try to tackle this so far, both
with javascript. The first would be to increment an index and send
that through the ajax function to the view that returns a new form.
The second would be to hook into the POST submission and munge the
data before it's passed back to django to save model instances.

It seems to me that something like this, while not common, has to have
been done before in web apps. I was wondering if there were some
established patterns to do this sort of thing, and if I am on the
right track. I have searched a few places including django snippets
and packages to see if something like this has been done before, but I
couldn't find anything. I'm not sure if I'm using the best search
terms.

-- 
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=en.



Discrepancy between model formset and the queryset it's based on

2010-09-01 Thread ses1984
Basically I have a queryset with N items in it, which I use to create
a model formset, which then has N+1 items in it. I'm not sure why this
is happening.

Here is a summary of the problem. Please forgive my crude methods for
gathering information (if anyone has feedback on that topic, I would
like to hear it)

http://dpaste.com/hold/237587/

-- 
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=en.



Re: Custom widgets in Model Formsets

2010-06-27 Thread ses1984
Thanks for spotting this! I can't believe I let myself make such a
basic error.

On Jun 27, 5:51 am, Daniel Roseman <dan...@roseman.org.uk> wrote:
> On Jun 27, 7:47 am, ses1984 <ses1...@gmail.com> wrote:
>
> > I am trying to use custom widgets in a model formset. I have tried to
> > achieve this by first defining the custom widget, then a form that
> > uses this widget, then passing this form as an argument to
> > modelformset_factory().
>
> > I don't think something is working right because if I check the type
> > of the form objects in my formset, the objects are my own custom
> > SliderInputs; however, when the very same formset is rendered, it
> > renders like the default widget. They don't render with any of the
> > content that I have added to the render method of SliderInput.
>
> > Below is the shell session demonstrating that I have SliderInput
> > widgets, then the actual class code that defines these.
>
> > I am using Django 1.1.1.
>
> Stop right there. 
> Fromhttp://docs.djangoproject.com/en/1.2/topics/forms/modelforms/#overrid...
>
>     "New in Django 1.2: The widgets attribute is new in Django 1.2."
>
> You've successfully defined a widgets attribute on the form's Meta
> class, but Django is doing absolutely nothing with it, because 1.1
> doesn't know about it.
>
> Instead, you'll need to override the field definition at the form
> level:
>
> class WeightSliderForm(forms.ModelForm):
>     amount = forms.FloatField(widget=SliderInput(attrs={
>                                                  'max':'1000',
>                                                  'min':'0',
>                                                  'step':'.001',
>                                                  'unit':'%',
>                                                  }))
>     class Meta:
>         model = Recipe
>
> --
> DR.

-- 
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=en.



Custom widgets in Model Formsets

2010-06-27 Thread ses1984
I am trying to use custom widgets in a model formset. I have tried to
achieve this by first defining the custom widget, then a form that
uses this widget, then passing this form as an argument to
modelformset_factory().

I don't think something is working right because if I check the type
of the form objects in my formset, the objects are my own custom
SliderInputs; however, when the very same formset is rendered, it
renders like the default widget. They don't render with any of the
content that I have added to the render method of SliderInput.

Below is the shell session demonstrating that I have SliderInput
widgets, then the actual class code that defines these.

I am using Django 1.1.1.


>>> from fd.access.models import Flavor, Recipe
>>> from fd.access.forms import WeightSliderForm
>>> from django.forms.models import modelformset_factory
>>>
>>> flavor = Flavor.objects.all()[1]
>>>
>>> RecipeFormSet = modelformset_factory(Recipe, form=WeightSliderForm)
>>> recipe_formset = RecipeFormSet(queryset=flavor.recipe_set.all())
>>>
>>> for recipe_form in recipe_formset.forms:
... print recipe_form.Meta.widgets
...
{'amount': }
{'amount': }
{'amount': }
{'amount': }
{'amount': }
>>>

###

class SliderInput(forms.widgets.TextInput):
"""
A slider widget to include in your form
"""

def render(self, name, value, attrs):
attributes = attrs
attributes['type'] = 'hidden'

res = super(SliderInput, self).render(name, value, attrs =
attributes)
res += ''
res += '%d' % (name, value)
res += '' %
name
res += '' % name
res += ''
return res

class Media:
css = {'screen':('/media/css/widgets/slider.css',)}
js = ('/media/js/widgets/slider.js',)

class WeightSliderForm(forms.ModelForm):
class Meta:
model = Recipe
fields = ['amount']
widgets = {
   'amount': SliderInput(attrs={
 'max':'1000',
 'min':'0',
 'step':'.001',
 'unit':'%',
 }),
   }

-- 
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=en.



Re: Testing custom management commands

2010-05-14 Thread ses1984
If I could add, in my tests, I was testing to see whether the command
executed successfully and I was inspecting the state of the database
after the command executed.

On May 14, 3:04 pm, ses1984 <ses1...@gmail.com> wrote:
> I am interested in writing unit tests to cover some custom commands I
> have written, but I'm unsure how I can pass options to these commands
> through my unittest.TestCase classes.
>
> I have a command to import data from my client's flat file system into
> Django models, which originally existed as a NoArgsCommand with no
> options. I tested it like this:
>
> class ImportDataTest(unittest.TestCase):
>
>     def setUp(self):
>         test_command = import_flatfile_data.Command()
>         test_command.handle_noargs()
>
> I have added a boolean flag option to this command, so I would like to
> split this test case in two, where one case sets up the command as
> with the flag set to true, and one case where the flag is false.
>
> I tried looking for testing coverage of django's own management
> commands, but I was unable to find those.
>
> --
> 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 
> athttp://groups.google.com/group/django-users?hl=en.

-- 
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=en.



Testing custom management commands

2010-05-14 Thread ses1984
I am interested in writing unit tests to cover some custom commands I
have written, but I'm unsure how I can pass options to these commands
through my unittest.TestCase classes.

I have a command to import data from my client's flat file system into
Django models, which originally existed as a NoArgsCommand with no
options. I tested it like this:

class ImportDataTest(unittest.TestCase):

def setUp(self):
test_command = import_flatfile_data.Command()
test_command.handle_noargs()

I have added a boolean flag option to this command, so I would like to
split this test case in two, where one case sets up the command as
with the flag set to true, and one case where the flag is false.

I tried looking for testing coverage of django's own management
commands, but I was unable to find those.

-- 
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=en.



Re: Problem with ModelFormSet

2009-11-13 Thread ses1984
Thanks so much for pointing this out! Some time ago, I did change the
model from a float to a decimal field. I did not think it would be an
issue. I was also just reading about needing to manually update the
database when the model is change. I didn't connect that with my
problem, because, using Django's admin interface, I am able to edit
existing objects with no problem.

I will look into this now; it seems very likely that this is my
problem.

--

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=.




Re: Problem with ModelFormSet

2009-11-13 Thread ses1984
Here's the traceback. Sorry I didn't post it before; I'm new at this.

Environment:

Request Method: POST
Request URL: http://192.168.0.10:8000/qc/newsession/
Django Version: 1.0.2 final
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
 'django.contrib.databrowse',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'django.contrib.formtools',
 'fd.homepage',
 'fd.metaparent',
 'fd.flavorbase',
 'fd.forms',
 'fd.qc',
 'fd.pdf_processing']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.csrf.middleware.CsrfMiddleware',
 'django.middleware.transaction.TransactionMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware')


Traceback:
File "/var/lib/python-support/python2.5/django/core/handlers/base.py"
in get_response
  86. response = callback(request, *callback_args,
**callback_kwargs)
File "/home/stachurski/fd/../fd/qc/views.py" in newsession
  86. instances = formset.save()
File "/var/lib/python-support/python2.5/django/forms/models.py" in
save
  389. return self.save_existing_objects(commit) +
self.save_new_objects(commit)
File "/var/lib/python-support/python2.5/django/forms/models.py" in
save_existing_objects
  410. saved_instances.append(self.save_existing
(form, obj, commit=commit))
File "/var/lib/python-support/python2.5/django/forms/models.py" in
save_existing
  377. return save_instance(form, instance, exclude=
[self._pk_field.name], commit=commit)
File "/var/lib/python-support/python2.5/django/forms/models.py" in
save_instance
  74. instance.save()
File "/var/lib/python-support/python2.5/django/db/models/base.py" in
save
  311. self.save_base(force_insert=force_insert,
force_update=force_update)
File "/var/lib/python-support/python2.5/django/db/models/base.py" in
save_base
  361. values = [(f, None, f.get_db_prep_save(raw
and getattr(self, f.attname) or f.pre_save(self, False))) for f in
non_pks]
File "/var/lib/python-support/python2.5/django/db/models/fields/
__init__.py" in get_db_prep_save
  192. return self.get_db_prep_value(value)
File "/var/lib/python-support/python2.5/django/db/models/fields/
__init__.py" in get_db_prep_value
  609. return connection.ops.value_to_db_decimal(self.to_python
(value),
File "/var/lib/python-support/python2.5/django/db/models/fields/
__init__.py" in to_python
  583. return decimal.Decimal(value)
File "/usr/lib/python2.5/decimal.py" in __new__
  654. "First convert the float to a
string")

Exception Type: TypeError at /qc/newsession/
Exception Value: Cannot convert float to Decimal.  First convert the
float to a string

--

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=.




Problem with ModelFormSet

2009-11-13 Thread ses1984
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:


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'%s'
% 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
###


{{ formset.management_form }}



Retain
Number
Lot
Amount
Reference
Passed
Rejected
Resample
Hold
Pending

{% for form in formset.forms %}

{{ form.instance.retain }}
{{ form.instance.product.number }}
{{ form.instance.amount }}
{{ form.instance.lot }}
{{ form.instance.product.retains.all.1 }}

{{ form }}

{% endfor %}






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



--

You received