2016-09-13 174 views
1

我正在使用Antonio Mele的Django-By-Example書籍學習Django。現在我到了第5章,現在我正在嘗試創建圖像共享應用程序。但是,儘管按照該章中的所有說明,當我嘗試在django開發服務器中添加來自外部URL的圖像時,我得到了ImportError。Django 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例如蟒蛇3.5翻譯。不知道爲什麼Django運行Python 2.7。 我不知道這個問題是否會出現,因爲forms.py和views.py模塊之間的'請求'名稱衝突?

/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 

回答

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

+0

的urllib和urllib2的位置之間的差異一個很好的討論謝謝,切換到urllib2修復了錯誤 – WaR1o

相關問題