Sunday, August 11, 2013

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


After adding a few more databases and views to my app, I suddenly get the error mentioned in the subject.

Not sure what happened .. everything worked as a charm before.

This only happens when the program tries to create a new record, I can change existing ones

It seems as if the "created_by" column is not accessible, after this line
   document = form.save(commit=False)
the debugger already shows the errro in the watch expression...

I marked the line where it fails in red below.

views.py

@login_required
def doc_details(request, doc_id=None):

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

    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 document.created_by is None:
                document.created_by = request.user
            document.save()
            return redirect(reverse('main_page.views.doc_index')) # Redirect after POST
    else:
        form = DocumentForm(instance=document) # An unbound form

    form.error_css_class = 'text-error'
    form.required_css_class = 'text-info'

    context = {'form': form,'navi': spc_globals.getnavigation(req=request)}

    if doc_id is None:
        context.update({
        'action': 'Add new document',
        'header': 'New document'
        })

    else:
        context.update({
        'action': 'Save document',
        'header': 'Edit document'
        })

    return render(request, 'main_page/edit_form.html', context)


models.py:

from django.db import models
from django.forms import ModelForm, DateField, DateInput
from django.conf import settings

# Main application settings.
class main_settings(models.Model):
    eventname = models.CharField('Eventname', max_length=200, blank=False)
    start_date = models.DateField('Begin date', help_text="Please use the following format: <em>YYYY-MM-DD</em>.")
    end_date = models.DateField('End date', help_text="Please use the following format: <em>YYYY-MM-DD</em>.")

# Input form for main application settings.
class mainSettingsForm(ModelForm):
    start_date = DateField(widget=DateInput(format='%d.%m.%Y'), input_formats=('%d.%m.%Y',), label='Begin date')
    end_date = DateField(widget=DateInput(format='%d.%m.%Y'), input_formats=('%d.%m.%Y',), label='End date')
    class Meta:
        model = main_settings
        exclude = ('date_created',)

# Document class
class main_documents(models.Model):
    doc_name = models.CharField("Document name", max_length=60)
    doc_link = models.URLField("Document URL/link")
    doc_description = models.TextField("Document description", blank=True, null=True)
    date_created = models.DateTimeField('Created on', auto_now_add=True, blank=True, null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, default='')

    class Meta:
        permissions = (
            ("view_documents", "Can see documents"),
            )


class DocumentForm(ModelForm):
    class Meta:
        model = main_documents
        exclude = ('date_created','created_by',)


class subevents(models.Model):
    active = models.BooleanField('Active', default=True)
    name = models.CharField("Subevent name", max_length=60, help_text='Specify the name')
    refcode_prefix = models.CharField("Reference code prefix", max_length=8, help_text='Please enter a prefix to be used as a reference code')
    refcode_counter = models.PositiveIntegerField(editable=False, default=1)
    description = models.TextField("Description", blank=True, null=True, default='', help_text='Enter a short description')
    start_date = models.DateField('Begin date', help_text="Please use the following format: <em>YYYY-MM-DD</em>.")
    end_date = models.DateField('End date', help_text="Please use the following format: <em>YYYY-MM-DD</em>.")
    date_created = models.DateTimeField('Created on', auto_now_add=True, blank=True, null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, default='')


class SubeventForm(ModelForm):
    class Meta:
        model = subevents
        exclude = ('date_created', 'created_by',)


class locations(models.Model):
    active = models.BooleanField('Active', default=True)
    name = models.CharField("Location name", max_length=60)
    address = models.TextField("Postal address", blank=True, default='')
    notes = models.TextField("Notes", blank=True, null=True, default='')
    date_created = models.DateTimeField('Created on', auto_now_add=True, blank=True, null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, default='')


class LocationsForm(ModelForm):
    class Meta:
        model = locations
        exclude = ('date_created', 'created_by',)


class levels(models.Model):
    active = models.BooleanField('Active', default=True )
    name = models.CharField("Level name", max_length=60)
    notes = models.TextField("Notes", blank=True, null=True, default='')
    location = models.ForeignKey(locations, blank=True, default='')
    date_created = models.DateTimeField('Created on', auto_now_add=True, blank=True, null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, default='')


class LevelsForm(ModelForm):
    class Meta:
        model = levels
        exclude = ('date_created', 'created_by',)



traceback:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/documents

Django Version: 1.5.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'main_page',
 'accounts',
 'south',
 'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\core\handlers\base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "D:\Dev\spcmanage\main_page\views.py" in doc_details
  109.             if document.created_by is None:
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\fields\related.py" in __get__
  384.                 rel_obj = qs.get(**params)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\query.py" in get
  379.         clone = self.filter(*args, **kwargs)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\query.py" in filter
  655.         return self._filter_or_exclude(False, *args, **kwargs)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  673.             clone.query.add_q(Q(*args, **kwargs))
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\sql\query.py" in add_q
  1266.                             can_reuse=used_aliases, force_having=force_having)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\sql\query.py" in add_filter
  1197.                 connector)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\sql\where.py" in add
  71.             value = obj.prepare(lookup_type, value)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\sql\where.py" in prepare
  339.             return self.field.get_prep_lookup(lookup_type, value)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_lookup
  322.             return self.get_prep_value(value)
File "D:\Python27\.virtualenvs\djellis\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  555.         return int(value)

Exception Type: ValueError at /documents
Exception Value: invalid literal for int() with base 10: ''

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