反转&#39;详细信息&#39;参数&#39;()&#39;和关键字参数&#39; {&#39; slug&#39;:&#39;&#39;}&#39;未找到。尝试了1种模式:[&#39;交易/(?P <slug> \\ d +)/ $&#39;]

时间:2016-07-09 16:35:02

标签: django django-models django-views slug

我使用Django为Post模型创建了post_create和post_detail视图。我想为新帖子创建一个slug,这样在点击post_list中的一些帖子后,他可以重定向到post_detail并生成一个独特的slug。当我运行我的服务器时,它会提出:反转&#39; detail&#39;参数&#39;()&#39;和关键字参数&#39; {&#39; slug&#39;:&#39;&#39;}&#39;未找到。尝试了1种模式:[&#39;交易/(?P \ d +)/ $&#39;]。如果有人对可能导致此错误的内容有任何指示,我将非常感激。

views.py:

def deal(request):
    today = timezone.now().date()
    queryset_list = Post.objects.active() #.order_by("-timestamp")

    if request.user.is_staff or request.user.is_superuser:
        queryset_list = Post.objects.all()

    query = request.GET.get("q")

    if query:
        queryset_list = queryset_list.filter(
                Q(from1__icontains=query)|
                Q(type_of_truck__icontains=query)|
                Q(Material_Name__icontains=query) |
                Q(To__icontains=query)|
                Q(Material_Type__icontains=query)
                ).distinct()

    paginator = Paginator(queryset_list, 2) # Show 25 contacts per page
    page_request_var = "page"
    page = request.GET.get(page_request_var)

    try:
        queryset = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        queryset = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        queryset = paginator.page(paginator.num_pages)


    context = {
        "object_list": queryset_list, 
        "from1": "List",
        "page_request_var": page_request_var,
        "today": today,
    }

    return render(request, 'before_login/deal.html', context) 

def post_create(request):
    # if not request.user.is_staff or not request.user.is_superuser:
    # raise Http404

    form = PostForm(request.POST or None)

    if form.is_valid():
        instance = form.save(commit=False)
        print(form.cleaned_data.get("from1"))
        instance.user = request.user
        instance.save()
        # message success
        messages.success(request, "Successfully Created")
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        "form": form,
    }
    return render(request, "loggedin_load/post_load.html", context)

def post_detail(request, slug=None): #retrieve
    #instance = Post.objects.get(id=1)
    instance = get_object_or_404(Post, slug=slug)

    if instance.date > timezone.now().date():
        if not request.user.is_staff or not request.user.is_superuser:
            raise Http404
    share_string = quote_plus(instance.Material_Type)

    context = {
        "from1": instance.from1,
        "instance": instance,
        "share_string": share_string
    }
    return render(request, "loggedin_load/post_detail.html", context)

urls.py:

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

models.py:

class Post(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)
    type_of_truck = models.CharField(max_length=20)
    date = models.CharField(max_length=20)
    slug = models.SlugField(unique=True)
    weight = models.DecimalField( max_digits=5, decimal_places=2)
    Material_Name = models.CharField(max_length=20)
    To = models.CharField(max_length=20)
    Number_Of_Truck = models.CharField(max_length=20)
    Time = models.CharField(max_length=20)
    Volume = models.CharField(max_length=20)
    Material_Type = models.CharField(max_length=20)
    #updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    objects = PostManager()

    def __unicode__(self):
        return self.from1

    def __str__(self):
        return self.from1

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})

    class Meta:
        ordering = ["-timestamp", "-Time"]



def create_slug(instance, new_slug=None):
    slug = slugify(instance.id)

    if new_slug is not None:
        slug = new_slug

    qs = Post.objects.filter(slug=slug).order_by("-id")
    exists = qs.exists()

    if exists:
        new_slug = "%s-%s" %(slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug


def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)



    pre_save.connect(pre_save_post_receiver, sender=Post)

deal.html:

 {% for obj in object_list %}


  <td scope="row">{{obj.date}}</td>
  <td> <a href='{{ obj.get_absolute_url }}'>{{ obj.from1 }}</a><br/></td>
  <td>{{obj.To}}</td>
  <td>{{obj.Material_Type}}</td>
  <td>{{obj.type_of_truck}}</td>
  <td>{{obj.Number_Of_Truck}}</td>
  <td>{{obj.weight}}</td>
  <td>Rs. 55000</td>
  <td><button type="button" id="bidbutton" class="btn btn-secondary fontsize align-centre bidbutton">Bid</button></td>
</tr>
{% endfor %}

post_detail.html:

{% load urlify %}

{% block head_title %}
{{ instance.from1 }} | {{ block.super }}
{% endblock head_title %}



{% block content %}
<div class='col-sm-6 col-sm-offset-3'>

 <!-- <h1>{{ title }} <small>{% if instance.draft %}<span    style='color:red;'>Draft</span>{% endif %} -->{{ instance.from1 }}</small></h1>
{% if instance.from1 %}
<p>{{ instance.Material_Type }}</p>
{% endif %}

回溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/deal/

Django Version: 1.9.7
Python Version: 3.4.4
Installed Applications:
['personal',
'custom_user',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'widget_tweaks']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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']


Template error:
In template C:\Users\sumanth\Desktop\django-custom-user- master\Project\mysite\personal\templates\before_login\deal.html, error at line 78
 Reverse for 'detail' with arguments '()' and keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['deal/(?P<slug>[\\w-]+)/$']   68 :       <th>Best Offer</th>
 69 :       <th></th>
 70 :     </tr>
 71 :   </thead>
 72 :   <tbody>
 73 :   <tr>
 74 :   {% for obj in object_list %}
 75 :   
 76 :   
 77 :       <td scope="row">{{obj.date}}</td>
 78 :       <td> <a href=' {{ obj.get_absolute_url }} '>{{ obj.from1 }}</a><br/></td>
 79 :       <td>{{obj.To}}</td>
 80 :       <td>{{obj.Material_Type}}</td>
 81 :       <td>{{obj.type_of_truck}}</td>
 82 :       <td>{{obj.Number_Of_Truck}}</td>
 83 :       <td>{{obj.weight}}</td>
 84 :       <td>Rs. 55000</td>
 85 :       <td><button type="button" id="bidbutton" class="btn btn-secondary fontsize align-centre bidbutton">Bid</button></td>
 86 :     </tr>
 87 :   {% endfor %}
 88 :     <!--<tr>

回溯:

File "c:\python34\lib\site-packages\django\core\handlers\base.py" in  get_response
149.                     response = self.process_exception_by_middleware(e, request)

File "c:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\sumanth\Desktop\django-custom-user-master\Project\mysite\personal\views.py" in deal
70.     return render(request, 'before_login/deal.html', context)

File "c:\python34\lib\site-packages\django\shortcuts.py" in render
67.             template_name, context, request=request, using=using)

File "c:\python34\lib\site-packages\django\template\loader.py" in   render_to_string
97.         return template.render(context, request)

File "c:\python34\lib\site-packages\django\template\backends\django.py" in render
95.             return self.template.render(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render
206.                     return self._render(context)

File "c:\python34\lib\site-packages\django\template\base.py" in _render
197.         return self.nodelist.render(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render
992.                 bit = node.render_annotated(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render_annotated
959.             return self.render(context)

File "c:\python34\lib\site-packages\django\template\loader_tags.py" in render
173.         return compiled_parent._render(context)

File "c:\python34\lib\site-packages\django\template\base.py" in _render
197.         return self.nodelist.render(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render
992.                 bit = node.render_annotated(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render_annotated
959.             return self.render(context)

File "c:\python34\lib\site-packages\django\template\loader_tags.py" in render
69.                 result = block.nodelist.render(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render
992.                 bit = node.render_annotated(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render_annotated
959.             return self.render(context)

File "c:\python34\lib\site-packages\django\template\defaulttags.py" in render
220.                     nodelist.append(node.render_annotated(context))

File "c:\python34\lib\site-packages\django\template\base.py" in render_annotated
959.             return self.render(context)

File "c:\python34\lib\site-packages\django\template\base.py" in render
1043.             output = self.filter_expression.resolve(context)

File "c:\python34\lib\site-packages\django\template\base.py" in resolve
709.                 obj = self.var.resolve(context)

File "c:\python34\lib\site-packages\django\template\base.py" in resolve
850.             value = self._resolve_lookup(context)

File "c:\python34\lib\site-packages\django\template\base.py" in _resolve_lookup
913.                             current = current()

File "C:\Users\sumanth\Desktop\django-custom-user-master\Project\mysite\personal\models.py" in get_absolute_url
47.         return reverse("posts:detail", kwargs={"slug": self.slug})

File "c:\python34\lib\site-packages\django\core\urlresolvers.py" in reverse
600.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "c:\python34\lib\site-packages\django\core\urlresolvers.py" in _reverse_with_prefix
508.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /deal/
Exception Value: Reverse for 'detail' with arguments '()' and keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['deal/(?P<slug>[\\w-]+)/$']

3 个答案:

答案 0 :(得分:2)

请再看一下错误:

  

使用参数'()'和关键字参数'{'slug':&gt;''}'找不到“详细信息”。尝试了1种模式:['deal /(?P \ d +)/ $']。

您是否识别网址'deal/(?P\d+)/$'

此网址似乎也具有名称'detail',并在posts/urls.py网址之前的post_detail中定义。确保您为网址指定的名称是唯一的。

我认为问题中包含的任何代码都在您的posts应用中。

修改

在使用真实数据和回溯更新问题后进行此编辑。

问题是,Posts模型中的所有条目都不是slug。因此,kwarg slug为空,这使reverse失败。每次调用模型的Posts方法时,您都可以定义一种方法,以根据create模型上的其他字段创建唯一的slug。 (您还需要覆盖PostsManager

您还可以使用pk代替slug来查找Posts个实例。默认情况下,pk可用于所有Django模型。

答案 1 :(得分:1)

我遇到了类似的问题,经过大量研究,我没有得到任何有帮助的答案,我来找我在模板中传递了url,lo和bekeeper的模板,但我没有使用正确的URL进行更改我将路径更改为使用slug而不是pk后的参数。

这是更改前模板中的url路径和url参数:

path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
<a href="{% url 'post-detail' post.pk %}" >

这是下面更改的网址路径和网址参数:

path('post/<str:category>/<str:slug>/', PostDetailView.as_view(), name='post-detail'),
<a href="{% url 'post-detail' post.category post.slug %}" >

我知道这个答案目前可能与您无关,但希望对您有所帮助。

答案 2 :(得分:0)

我不确定您是否需要指定posts:detail,这在模型中应该足够了。您的网址名为detail,因此请尝试detail

models.py

def get_absolute_url(self):
    return reverse("detail", kwargs={"slug": self.slug})
相关问题