Sunday, August 11, 2013

Re: Suddenly I keep getting this error: invalid literal for int() with base 10: ''


Finally - FIXED!

After a some experimenting with the command line I found out that I can not access the foreign key field if there is no actual record.

So this throws the error as well:

>>> doc = main_documents.objects.create(doc_name="test", doc_description="description")
>>> doc.created_by

But after assigning a value, created_by is available:

>>> from accounts.models import UserAccount
>>> user = UserAccount.objects.get(pk=1)
>>> doc.created_by = user
>>> doc.created_by
<UserAccount: myemail@invalid.com>


So finally I changed my code to this:

(maybe there is some more elegant way, but currently the main thing is that it works now :-)

def doc_details(request, doc_id=None):

    isNewRecord = False

    if doc_id is not None:
        document = main_documents.objects.get(pk = doc_id)
    else:
        document = None
        isNewRecord = True

    if request.method == 'POST': # If the form has been submitted...
        form = DocumentForm(request.POST, instance=document) # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            document = form.save(commit=False)
            if isNewRecord or document.created_by is None:
                document.created_by = request.user

            document.save()


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment