Reputation: 661
I have database with records, and I like to use "title" record as link to the article, but problem is that on model slug is not defined. I not entirely sure if i can use urls.py and views.py only to generate url path to the article. So far here is my code.
class ArticleView(ListView):
template_name = 'article.html'
def get_queryset(self):
article = self.kwargs.get('feed_title', None)
return article
def get_context_data(self, request, **kwargs):
context = super(ArticleView, self).get(request, **kwargs)
return context
and my url:
url(r'^(?P<article>[-\w]+)/$', ArticleView.as_view(), name='article')
Upvotes: 2
Views: 708
Reputation: 661
I solved my issue, I added slugfield to My model as was suggested by @Gary, then I run South migration:
python manage.py schemamigration Myapp --auto
python manage.py migrate Myapp
Then for create the slug field entries for all my existing data. I have used Django shell:
python manage.py shell
from django.template.defaultfilters import slugify
from MyApp.models import MyModel
First just for test:
>>> for obj in MyModel.objects.all():
... obj.slug = slugify(obj.title)
... print(obj.slug)
Then generate slug and save:
>>> for obj in MyModel.objects.all():
... obj.slug = slugify(obj.title)
... obj.save()
...
>>>
With this I created slug-url for more than 3000 entries. Now I will focus how to create a template and serve each entry with url as title for article.
Upvotes: 1
Reputation: 3115
Just add a slugfield to your model and specify a default value calculated from your name field. If you're using South for your migrations (and if you're not you should be!) then it will use the default value when migrating existing instances. Django's slugify feature may also be useful for adding slugs to existing articles.
Upvotes: 0