gpt4 book ai didi

python - Django ImportError 无法导入名称请求

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:12 24 4
gpt4 key购买 nike

我正在使用 Antonio Mele 的 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 模块之间的“request”名称冲突而出现?

/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

最佳答案

这是由于 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 之间的区别的很好的讨论。

关于python - Django ImportError 无法导入名称请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com