我正在使用安东尼奥·梅尔的书“Django-By-Example”来学习Django。现在我已经达到第5章,现在我正在尝试创建图像共享应用程序。但是,尽管遵循了该章中的所有说明,但当我尝试在django开发服务器中添加外部URL中的图像时,我得到了ImportError。
ImportError at /images/create/
cannot import name request
Request URL: http://127.0.0.1:8000/images/create/?title=%20Django%20and%20Duke&url=http://upload.wikimedia.org/wikipedia/commons/8/85/Django_Reinhardt_and_Duke_Ellington_(Gottlieb).jpg.
Django Version: 1.8.6
Exception Location: /home/ciotar/projects/VirtualEnvs/env/bookmarks/bookmarks/images/forms.py in <module>, line 1
Python Version: 2.7.11
我正在使用Pycharm,并从活动的virtualenv实例中设置了python 3.5解释器。不知道为什么Django运行python 2.7。 我想知道这个问题是否会因为“请求”问题而出现。 forms.py和views.py modules之间的名称冲突?
/images/urls.py
urlpatterns = [
url(r'^create/$', views.image_create, name='create'),
]
/images/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import ImageCreateForm
@login_required
def image_create(request):
"""
View for creating an Image using the JavaScript Bookmarklet.
"""
if request.method == 'POST':
# form is sent
form = ImageCreateForm(data=request.POST)
if form.is_valid():
# form data is valid
cd = form.cleaned_data
new_item = form.save(commit=False)
# assign current user to the item
new_item.user = request.user
new_item.save()
messages.success(request, 'Image added successfully')
# redirect to new created item detail view
return redirect(new_item.get_absolute_url())
else:
# build form with data provided by the bookmarklet via GET
form = ImageCreateForm(data=request.GET)
return render(request, 'images/image/create.html', {'section': 'images',
'form': form})
/images/forms.py
from urllib import request
from django.core.files.base import ContentFile
from django.utils.text import slugify
from django import forms
from .models import Image
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description')
widgets = {
'url': forms.HiddenInput,
}
def clean_url(self):
url = self.cleaned_data['url']
valid_extensions = ['jpg', 'jpeg']
extension = url.rsplit('.', 1)[1].lower()
if extension not in valid_extensions:
raise forms.ValidationError('The given URL does not match valid image extensions.')
return url
def save(self, force_insert=False, force_update=False, commit=True):
image = super(ImageCreateForm, self).save(commit=False)
image_url = self.cleaned_data['url']
image_name = '{}.{}'.format(slugify(image.title),
image_url.rsplit('.', 1)[1].lower())
# download image from the given URL
response = request.urlopen(image_url)
image.image.save(image_name,
ContentFile(response.read()),
save=False)
if commit:
image.save()
return image
答案 0 :(得分:3)
这是因为Python版本存在差异。
在Python 2.7中,您可能必须替换:
from urllib import request
在forms.py
中
import urllib2
urllib2 > Request
模块再次没有urlopen
方法。所以你必须更换行
response = request.urlopen(image_url)
使用:
response = urllib2.urlopen(image_url)
在forms.py
关于此SO post
的urllib和urllib2之间的差异,这是一个很好的讨论