I asked in past time about how generate an url with similar caracterist starting from an ID you said me that is better use slugs to do that. On this time I wanna generate dinamics urls with slugs. My objective is obtain this result:
I have five products that I named cards in models.py (Ysera, Neltharion, Nozdormu, Alexstrasza, Malygos). I need the respective url of each of the products:
localhost:8000/card/ysera
localhost:8000/card/neltharion
localhost:8000/card/nozdormu ... etc.
I try to generate these urls but i dont know if I made a good applying of commands, either I don't know how I can specify the id card like the main name of the card (ysera, neltharion...). I was trying to follow an answer posted here in this community a little blind and this is my "reconfiguration":
Here my views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from dracoin.apps.synopticup.models import card
from dracoin.apps.home.forms import ContactForm,LoginForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
def shop(request):
tarj = card.objects.filter(status=True)
ctx = {'tarjetas':tarj}
return render_to_response('home/shop.html',ctx,context_instance=RequestContext(request))
def singleCard(request, slug, id):
try:
tarj = card.objects.get(slug=slug, id=id_tarj)
except ObjectDoesNotExist:
tarj = get_object_or_404(card, id=id_tarj)
return render_to_response('home/singleCard.html',ctx,context_instance=RequestContext(request))
My urls.py (I have an urls.py by app and the main urls.py):
url(r'^card/(?P<slug>[-\w]+)/(?P<id_tarj>\d+)/$','dracoin.apps.home.views.singleCard',name='vista_single_card'),
My models.py:
class card(models.Model):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.nombre
My common template for all cards:
{% extends 'base.html' %}
{% block title %} Tarjeta {{card.nombre}} {% endblock %}
{% block content %}
<h1>{{ card.nombre }}</h1><br>
<p> {{ card.descripcion }}</p>
{% endblock %}
I don't know if my slug building in views.py was find, I'm convinced that the urls.py is bad but i don't know how build it?
please excuse me if I edit my own question to prolong it, Recently I'm trying to learn django by my side and I have many gaps in my learning
apologizeme in advance my extensive question and if I overlook something.
Thanks!!
This line:
tarj = card.objects.get(slug=slug, id=id_tarj)
tries to load a card
object where the id
field is set to is id_tarj
and the slug
field is set to slug
. Your model does not have a field named slug
. You will need to add one.
A good candidate for it would be a SlugField
- https://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield
You will need to make sure that your slug field contains a proper value in each case.