Saturday, July 28, 2012

Re: form.save() fails - due to missing field?

On Sat, Jul 28, 2012 at 9:31 AM, Sithembewena Lloyd Dube <zebra05@gmail.com> wrote:
Hi all,

I have a view where if request.method == 'POST', I need to call save. Basically, it's a registration form and the entity is a user (not the base Django user, but a custom model). An existing user refers another person, when they click the link they come to a registration page.

I have a problem where I try to call save:

            form = SubmitReferralForm(data=request.POST)
            if form.is_valid():
                try:
                    registered_user.referral_set.get(email_address=form.instance.email_address, status=1)
                    msg = 'This email address has already been referred. Try another?'
                except Referral.DoesNotExist:
                    form.instance.status = 1
                    referral = form.save()

The form looks as follows:

class SubmitReferralForm(forms.ModelForm):

    class Meta:
        model = Referral
        exclude = (
            'section', 'referrer', 'status', 'time_added',
        )

Now, the section referred to here is hideen in the form but I need to provide it before calling save. Problem is, the referred user's section is in one app, the referrer's section is in another - but they should both be the same. The exception is:


I don't quite follow what you are saying here. You have two different Section models in two different apps? If so, that sounds like not the best approach.

The exception you are getting is due to excluding section from this form and not providing a value for it before attempting to save the form/model. The code you show is already solving this problem for the Referral status field, you must somehow do the same thing for the section. The key is you must set section before attempting to save the new model. As noted above I can't quite follow what you've said about section so can't advise on how to set it in this case, but it must be set to something before you can save a new Referral model instance.

Karen
--
http://tracey.org/kmt/

--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment