On Mon, Apr 16, 2012 at 4:11 PM, Mario Gudelj <mario.gud...@gmail.com> wrote: > Hi Djangoers, > > I have an issue I can't work out. This is the situation: > > I have a model called payment, which has a custom constructor which takes a > parameter. This is the code: > > class Payment(models.Model): > id = models.AutoField(primary_key=True) > amount = models.FloatField("Total payment amount") > ... > > def __init__(self, business, *args, **kwargs): > super(Payment, self).__init__(*args, **kwargs) > self.business = business >
As you've found out, this causes pain. Your model instances need to be constructable without arguments for most automatic form related stuff to happen. In this specific case, your problem is that when you do not pass an instance to a ModelForm based upon this model, the code will by default attempt to construct an empty instance, without passing any arguments, and an exception is raised. To work around this, you have to avoid that scenario. You can override the __init__ method of the form, and examine the instance out of kwargs. If an instance has not been passed through, you need to construct an empty instance there, and pass it to the form. This will solve this specific use of ModelForms and your model. It would not, for instance, make the admin site suddenly start working with this model. In general though, you should look at your design: In order to construct an instance of your class, your design says that you must pass additional information to that class. However, your class represents a row in a database table - why does an instance of your class rely on information that is not persisted in the database? How do you expect something like "Payment.objects.get(id=1)" to work? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@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.