You probably don't want to use the name directly, you should probably look at creating a slug from the name and store it in a SlugField on your model.
https://docs.djangoproject.com/en/1.8/ref/models/fields/#slugfield
https://docs.djangoproject.com/en/1.8/ref/utils/#module-django.utils.text
Your URL regex already looks correct to capture a slug.
At that point it's just a matter of pulling the object via the slug in your view:
fruit = get_object_or_404(Fruit, slug=fruit_name)
Of course that's assuming that your SlugField is named 'slug'. Make sure to read up on slugs since they need to be unique, and generating them may be a challenge.
-James
On Aug 13, 2015 12:18 PM, "I. Dié" <idie.levano@gmail.com> wrote:
-- Hi evrybody,--
Here is my model:
# fruits/models
Class Fruit (models.Model):
name = models.CharField(max_length = 33,
choices = NAME_CHOICES, default = MANGO)
# and so on...
# fruits/views
def fruit(request, fruit_name):
fruit = get_object_or_404(Fruit)
return render(request, 'fruits/fruit.html', {'fruit': fruit})
# fruits/urls
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^(?P<fruit_name>[-\w]+)/$', views.fruit, name='fruit'),
]
When I used fruit_id, everything was ok.
But I want to know how to use Fruit.name (a string) as url's parameter instead of fruit_id like this: myverybigmarket/fruits/mango better than myverybigmarket/fruits/1
Ps: this is my first python/django project.
Thanks
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/404e6ef5-99d7-4e38-8bf1-978b8690d733%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciV_hX6zpDRZMEgNnU_9Z4Pkxqgozs-HwiAJWmigiVoRqA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment