在Django中使用slug字段

时间:2015-05-12 16:26:06

标签: python django

我做了一个slug字段,我进行了迁移。我的slug字段称为slug,它在站点管理中可见,但它无法正常工作。

我的浏览器告诉我:

/ Error /的TypeError     detail()得到了一个意外的关键字参数'slug'

models.py

from django.db import models

class Question(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(null=True, blank=True)
    description = models.CharField(max_length=200)
    data_published = models.DateTimeField('date published')
    large_description = models.TextField(max_length=20000)

    def __str__(self):             
    return self.title

    def save(self):
    if not self.id:
        self.s = slugify(self.q)

    super(test, self).save()

def was_published_recently(self):
    return self.datum_objave >= timezone.now() - datetime.timedelta(days=1)

urls.py

from django.conf.urls import include,  url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin


urlpatterns = [
   url(r'^$', 'books.views.index', name='index'),
   url(r'^admin/', include(admin.site.urls)),
   url(r'^(?P<slug>[\w_-]+)/$', 'books.views.detail', name='detail'), 
]   

urlpatterns += staticfiles_urlpatterns()

的index.html

{% extends "master.html"  %} 
{% block h1 %} 
<div class="box first">
<div class="row">
    <div class="container">
        {% for question  in latest_question_list %}
            <div class="col-xs-12 col-sm-4 col-md-3">
                <div class="center">
                    <a href="{{ question.slug }} " i class="icon-credit-card icon-md icon-color1"></a>
                    <h4>{{ question.title }} </h4>
                    <p>{{ question.description }}</p>
                </div>
            </div>
        {% endfor %}
    </div>
</div>

{% endblock %}
{% block title  %} Index {% endblock %}

admin.py

 from django.contrib import admin

 from .models import Question


class QuestionAdmin(admin.ModelAdmin):
question_fields = {"slug": ("title",)}

admin.site.register(Question, QuestionAdmin)

views.py

from django.shortcuts import render
from .models import Question


def index(request):
    latest_question_list = Question.objects.all()
    context = {'latest_question_list': latest_question_list}
    return render(request, 'papers/index.html', context)

def detail(request, book_title):
    question = Question.objects.get(title=book_title)
    return render(request, 'books/detail.html', {'question': question})`

detail.html

{% extends "master2.html"  %}
{% block h1 %} 
<div class="center">
    <h4>{{question.title}} </h4>
    <p>{{question.large_description}}</p>
</div>
{% endblock %}
{% block title  %} Detail {% endblock %}

1 个答案:

答案 0 :(得分:3)

urls.py的这一部分(?P<slug>[\w_-]+)表示有一个视图接受名为slug的参数,如果Django无法找到该视图,它会抱怨。所以你的观点应该是这样的:

def detail(request, slug):
    question = Question.objects.get(slug=slug)
    return render(request, 'papers/detail.html', {'question': question})

<强>更新
不要在模板中手动创建网址也是一个好主意:

<a href="{% url 'detail' question.slug %}">{{ question.naslov }}</a>