2016-03-13 153 views
1

我想在我的web應用程序中使用Pillow添加用戶可上傳的圖像。我創建了一個Django上傳模型並在管理員中註冊。只要我使用管理控制檯添加了一張照片,我收到以下錯誤消息。最初,該網站正在無一不精Django NoReverseMatch在/

的錯誤

NoReverseMatch at/

Reverse for 'thing_detail' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['things/(?P<slug>[-\\w]+)/$'] 

Request Method:  GET 
Request URL: http://localhost:8000/ 
Django Version:  1.8.4 
Exception Type:  NoReverseMatch 
Exception Value:  

Reverse for 'thing_detail' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['things/(?P<slug>[-\\w]+)/$'] 

Exception Location:  /usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 496 
Python Executable: /usr/bin/python 
Python Version:  2.7.6 
Python Path:  

['/home/shashank/development/hellowebapp/hellowebapp', 
'/usr/lib/python2.7', 
'/usr/lib/python2.7/plat-x86_64-linux-gnu', 
'/usr/lib/python2.7/lib-tk', 
'/usr/lib/python2.7/lib-old', 
'/usr/lib/python2.7/lib-dynload', 
'/usr/local/lib/python2.7/dist-packages', 
'/usr/lib/python2.7/dist-packages', 
'/usr/lib/python2.7/dist-packages/PILcompat', 
'/usr/lib/python2.7/dist-packages/gtk-2.0', 
'/usr/lib/pymodules/python2.7', 
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] 

Server time: Sun, 13 Mar 2016 18:54:31 +0000 

Urls.py

from collection.backends import MyRegistrationView 
from django.conf.urls import include, url 
from django.contrib import admin 
from collection import views 
from django.conf import settings 
from django.views.generic import TemplateView 
from django.contrib.auth.views import (
    password_reset, 
    password_reset_done, 
    password_reset_confirm, 
    password_reset_complete 
    ) 

urlpatterns = [ 
    url(r'^$', views.index, name='home'), 

    url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'), 

    url(r'^contact/$',TemplateView.as_view(template_name='contact.html'),name='contact'), 

    url(r'^things/(?P<slug>[-\w]+)/$','collection.views.thing_detail',name='thing_detail'), 

    url(r'^things/(?P<slug>[-\w]+)/edit/$','collection.views.edit_thing',name='edit_thing'), 

    url(r'^things/(?P<slug>[-\w]+)/edit/weight$','collection.views.edit_weight',name='edit_weight'), 

    url(r'^things/(?P<slug>[-\w]+)/delete/weight$','collection.views.remove_weight',name='remove_weight'), 

    #WORKING url(r'^things/(?P<pk>\d+)/remove/$', 'collection.views.remove_weight', name='remove_weight'), 

    url(r'^things/$',TemplateView.as_view(template_name='weight_removed.html'),name='weight_removed'), 

    url(r'^(?P<slug>[\w\d-]+)/(?P<pk>\d+)/$','collection.views.remove_weight',name='remove_weight'), 






    #url(r'^edit/(?P<slug>\d+)/weights$', 'collection.views.AddWeight',name='AddWeight'), 
    # the new password reset URLs 
    url(r'^accounts/password/reset/$',password_reset,{'template_name':'registration/password_reset_form.html'},name="password_reset"), 
    url(r'^accounts/password/reset/done/$',password_reset_done,{'template_name':'registration/password_reset_done.html'},name="password_reset_done"), 
    url(r'^accounts/password/reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',password_reset_confirm,{'template_name':'registration/password_reset_confirm.html'},name="password_reset_confirm"), 
    url(r'^accounts/password/done/$',password_reset_complete,{'template_name':'registration/password_reset_complete.html'},name="password_reset_complete"), 


    #setup additional registeration page 
    url(r'^accounts/register/$',MyRegistrationView.as_view(),name='registration_register'), 
    url(r'^accounts/create_thing/$','collection.views.create_thing',name='registration_create_thing'), 

    url(r'^accounts/',include('registration.backends.default.urls')), 
    url(r'^admin/', include(admin.site.urls)), 


] 

if settings.DEBUG: 
    urlpatterns += [ 
     url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}), 
    ] 

模式的.py

from django.db import models 
from django.contrib.auth.models import User 
from django.db import models 
from django.utils import timezone 

class Thing(models.Model): 
    name = models.CharField(max_length=255) 
    description = models.TextField() 
    slug = models.SlugField(unique=True) 
    user = models.OneToOneField(User, blank=True, null=True) 


class Weight(models.Model): 
    date = models.DateTimeField(default=timezone.now) 
    weight_value = models.CharField(max_length=255) 
    thingRA = models.ForeignKey(Thing,related_name="weights") 

    class Meta: 
     order_with_respect_to = 'thingRA' 
     ordering = ['date'] 

def get_image_path(instance, filename): 
    return '/'.join(['thing_images', instance.thing.slug, filename]) 

class Upload(models.Model): 
    thing = models.ForeignKey(Thing, related_name="uploads") 
    image = models.ImageField(upload_to=get_image_path) 

Admin.py

from django.contrib import admin 
# import your model 
from collection.models import Thing, Weight, Upload 


class ThingAdmin(admin.ModelAdmin): 
    model = Thing 
    list_display = ('name', 'description',) 
    prepopulated_fields = {'slug': ('name',)} 
    # and register it 

admin.site.register(Thing, ThingAdmin) 

class WeightAdmin(admin.ModelAdmin): 
    model = Weight 
    list_display = ('date','weight_value',) 

admin.site.register(Weight, WeightAdmin) 


class UploadAdmin(admin.ModelAdmin): 
    list_display = ('thing',) 
    list_display_links = ('thing',) 

# and register it 
admin.site.register(Upload, UploadAdmin) 

base.html文件

{% load staticfiles %} 

<!DOCTYPE html> 
<html> 
<head> 

    <title> 
    {% block title %} 
    WEB PAGE BY SHASHANK 
    {% endblock title %} 
    </title> 
    <link rel="stylesheet" href="{% static 'css/style.css' %}" /> 

</head> 
<body> 
     <div id="page"> 
     <div id="logo"> 
      <h1><a href="/" id="logoLink">S PORTAL</a></h1> 
     </div> 
     <div id="nav"> 
      <ul> 
       <li><a href="{% url 'home' %}">Home</a></li> 
       <li><a href="{% url 'about' %}">About</a></li> 
       <li><a href="{% url 'contact' %}">Contact</a></li> 

     {% if user.is_authenticated %} 
      <li><a href="{% url 'auth_logout' %}">Logout</a></li> 

      <li><a href="{% url 'thing_detail' slug=user.thing.slug %}">My Profile</a></li> 

     {% else %} 
      <li><a href="{% url 'auth_login' %}">Login</a></li> 

     <li><a href="{% url 'registration_register' %}">Register</a></li> 
     {% endif %} 
     </ul> 
     </div> 


     {% block content %}{% endblock content %} 


     <div id="footer"> 
      <p> 
     Webpage made by <a href="/" target="_blank">SHASHANK</a> 
      </p> 
     </div> 
    </div> 
</body> 
</html> 

View.py

from django.shortcuts import render,redirect,get_object_or_404 
from collection.models import Thing, Weight 
from collection.forms import ThingForm, WeightForm, ThingWeightFormSet 
from django.template.defaultfilters import slugify 
from django.contrib.auth.decorators import login_required 
from django.http import Http404 
from django.views.decorators.csrf import csrf_protect 
from django.views.generic import ListView, CreateView, UpdateView 
from django import forms 

def index(request): 
    things = Thing.objects.all() 
    return render(request,'index.html',{'things':things,}) 

def thing_detail(request, slug): 
    # grab the object... 
    thingRA = Thing.objects.get(slug=slug) 
    weights = thingRA.weights.all().order_by('-date') 
    # and pass to the template 
    return render(request, 'things/thing_detail.html', {'thing': thingRA, 'weights':weights,}) 

def edit_thing(request, slug): 
    # grab the object 
    thing = Thing.objects.get(slug=slug) 
    # set the form we're using 
    form_class = ThingForm 

    # if we're coming to this view from a submitted form 
    if request.method == 'POST': 
     # grab the data from the submitted form and apply to 
     # the form 
     form = form_class(data=request.POST, instance=thing) 
     if form.is_valid(): 
      # save the new data 
      form.save() 
      return redirect('thing_detail', slug=thing.slug) 
# otherwise just create the form 
    else: 
     form = form_class(instance=thing) 

# and render the template 
    return render(request, 'things/edit_thing.html', {'thing': thing,'form': form,}) 

def create_thing(request): 
    form_class = ThingForm 
    if request.method == 'POST': 
     form = form_class(request.POST) 
     if form.is_valid(): 
      thing = form.save(commit=False) 
      thing.user = request.user 
      thing.slug = slugify(thing.name) 
      thing.save() 
      slug = slugify(thing.name) 
      return redirect('thing_detail', slug=thing.slug) 
    else: 
     form = form_class() 

    return render(request,'things/create_thing.html', {'form': form,}) 


def edit_weight(request, slug): 
    thing = get_object_or_404(Thing, slug=slug) 
    if request.method == "POST": 
     form = WeightForm(request.POST) 
     if form.is_valid(): 
      weight = form.save(commit=False) 
      weight.thingRA = thing 
      weight.save() 
      return redirect('thing_detail', slug=thing.slug) 
    else: 
     form = WeightForm() 
    return render(request, 'things/edit_weight.html', {'form': form}) 

"""WORKING WEIGHT 
def remove_weight(request, pk): 
      weight = get_object_or_404(Weight, pk=pk) 
      thing_pk = weight.thingRA.pk 
      weight.delete() 
      return redirect('weight_removed') 
""" 


def remove_weight(request, pk, slug): 
      weight = get_object_or_404(Weight, pk=pk) 
      thing = get_object_or_404(Thing, slug=slug) 
      thing_pk = weight.thingRA.pk 
      weight.delete() 
      return redirect('thing_detail', slug=slug) 


@login_required 
def edit_thing(request, slug): 
    # grab the object... 
    thing = Thing.objects.get(slug=slug) 
    # make sure the logged in user is the owner of the thing 
    if thing.user != request.user: 
     raise Http404 
     # set the form we're using... 
    form_class = ThingForm 
    # if we're coming to this view from a submitted form, 
    if request.method == 'POST': 
     # grab the data from the submitted form and 
     # apply to the form 
     form = form_class(data=request.POST, instance=thing) 
     if form.is_valid(): 
      # save the new data 
      form.save() 
      return redirect('thing_detail', slug=thing.slug) 
    # otherwise just create the form 
    else: 
     form = form_class(instance=thing) 
     # and render the template 
    return render(request, 'things/edit_thing.html', {'thing': thing,'form': form,}) 

回答

0

終於明白了。代碼中沒有任何問題。其實我只需要從Django的管理面板註銷。由於正在登錄管理控制檯,因此其他用戶無法與其相關數據交互。

1

你可能在與具有空塞屬性的'thing'對象模板使用{% url 'thing_detail' slug=thing.slug %}

爲模板添加一個條件來檢查對象中現有的段落,以便不調用模板標記或確保沒有任何Thing對象具有空白段落。

+0

按照Antoine的說明,我使用殼檢查了一個空的slu slu。我沒有找到任何。即使在我的模板中使用{%url'thing_detail'slug = thing.slug%}之後,該網站仍可以正常工作。 –

2

我會說你有一件事與slug=""。你可以看看這個使用Django殼:

from yourapp.models import Thing 
Thing.objects.get(slug='') 

根據你的模型定義slug可以是空白的,但你的URL模式不接受空塞。你將不得不修復你的slug字段或你的url模式。

+0

按照你的說法試過。沒有一個slu or或一個空的slu field領域,我沒有找到入境。此外,如果是這種情況,那麼在我對添加圖像進行更改之前,網站是如何運作的。請幫助我。 –

+0

我以爲錯誤來自管理員,因爲您向我們展示了admin.py,但它看起來像來自您的根URL。請顯示您的主頁視圖和模板。 –

+0

突出顯示的錯誤顯示在我的base.html中的「{%url'thing_detail'slug = user.thing.slug%}」中。我將這添加爲另一個問題的解決方案,之前這一切都很好。我做的唯一更改是添加上傳模型和Urls.py中的最後幾行和Admin.py –