尝试使用Django上传图像时int()的文字无效

时间:2014-12-27 13:53:29

标签: django image-uploading

尝试通过Django表单上传图片时遇到问题。实际上我做了与https://coderwall.com/p/bz0sng/simple-django-image-upload-to-model-imagefield相同的事情但是当我发布包含文本字段和图像字段的表单时,我收到此错误:ValueError at /prive/nouveau-projet invalid literal for int() with base 10

这是我的模型和我的表单模型:

class Projet(models.Model):
    title = models.CharField(max_length=100)
    subtitle = models.CharField(max_length=100)
    content = models.CharField(max_length=4000)
    image = models.ImageField(upload_to='projets/')

def __unicode__(self):
    return self.title

class ProjetForm(forms.Form):
    title = forms.CharField(label="", max_length=100)
    subtitle = forms.CharField(label="", max_length=100)
    content = forms.CharField(label="", max_length=4000, widget=forms.Textarea)
    image = forms.ImageField(label="")

以下是我views.py的代码:

def newProject(request):
if request.method == 'POST':
    form = ProjetForm(request.POST, request.FILES)
    if form.is_valid():
        title = form.cleaned_data["title"]
        subtitle = form.cleaned_data["subtitle"]
        content = form.cleaned_data["content"]
        image = form.cleaned_data["image"]
        p = Projet(title, subtitle, content, image)
        print(p.image)
        p.save()
    else:
        print('fail')
    return HttpResponse()
else:
    pf = ProjetForm()
    return render(request, 'newProject.html', locals())

这是一个完整的追溯:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/prive/nouveau-projet

Django Version: 1.7
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'myapp')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/micael/Documents/web/site-omega/omega/myapp/views.py" in newProject
  133.          p.save()
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/base.py" in save
  590.                        force_update=force_update, update_fields=update_fields)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/base.py" in save_base
  618.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/base.py" in _save_table
  680.                                       forced_update)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/base.py" in _do_update
  710.         filtered = base_qs.filter(pk=pk_val)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/query.py" in filter
  691.         return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/query.py" in _filter_or_exclude
  709.             clone.query.add_q(Q(*args, **kwargs))
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/sql/query.py" in add_q
  1287.         clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/sql/query.py" in _add_q
  1314.                     current_negated=current_negated, connector=connector)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/sql/query.py" in build_filter
  1186.             condition = self.build_lookup(lookups, col, value)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/sql/query.py" in build_lookup
  1094.                     return final_lookup(lhs, rhs)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/lookups.py" in __init__
  82.         self.rhs = self.get_prep_lookup()
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/lookups.py" in get_prep_lookup
  85.         return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/fields/__init__.py" in get_prep_lookup
  646.             return self.get_prep_value(value)
File "/Library/Python/2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/fields/__init__.py" in get_prep_value
  915.         return int(value)

Exception Type: ValueError at /prive/nouveau-projet
Exception Value: invalid literal for int() with base 10: 'zlerj'

1 个答案:

答案 0 :(得分:1)

不确定您遇到此特定错误的原因,但可能建议您尝试使用ModelForm自动保存表单的更简单方法:

class Projet(models.Model):
    title = models.CharField(max_length=100)
    subtitle = models.CharField(max_length=100)
    content = models.TextField()
    image = models.ImageField(upload_to='projets/')

    def __unicode__(self):
        return self.title

class ProjetForm(forms.ModelForm):
    class Meta:
        model = Projet

然后,您只需要在验证后执行form.save()

def newProject(request):
    if request.method == 'POST':
        form = ProjetForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/redirect_url/")
    else:
        form = ProjetForm()
    return render_to_response('newProject.html', locals(), context_instance=RequestContext(request))