How to set up my urls with posts/1, posts/2, etc? - django

I'm following a few of the basic django blog tutorials. The part I am stuck on is how to set variables in my urls.
I want my urls to look like:
posts/1
posts/2
posts/3
Currently when i visit my index.html i see the list of blog posts (just the titles), and when I hover the cursor over each link it does show posts/1, posts/2, etc.
The problem is that when I click on these links, it basically just refreshes the page and does not show the detailed view.
my urls.py currently looks like this:
url(r'^posts/', index),
url(r'^posts/(?P<post_id>[0-9]+)/$', detailedview),
I'm not sure exactly what (?P[0-9]+)/$', does and I'm assuming this is the problem because detailedview is never being called.
This method is inside my views.py but again, it is never being called.
def detailedview(request, post_id):
targetpost = Post.objects.get(id="post_id")
context = {'targetpost': targetpost}
return render(request, 'posts/detailedview.html', context)

Your question about the second URL:
(?P<post_id>[0-9]+) is a regex that means "set the post_id argument to the value of any number with one or more digits (more info at https://docs.python.org/2/library/re.html.)
The way to fix your problem is to add a $ to the end of the first pattern, so it looks like this:
url(r'^posts/$', index),
This will make it only match the URL /posts/.
There is also a problem with your view: the line
targetpost = Post.objects.get(id="post_id")
should be:
targetpost = Post.objects.get(id=post_id)
This will make Django look for the Post with the id specified in the variable post_id, rather than the Post with the id that equals the string "post_id"

Related

Django pass known exact string as a url parameter

I have two urls in dispatcher pointing the same view
path('posts/top/', posts, name='top'),
path('posts/new/', posts, name='new'),
I want view start as follows:
def posts(request, ordering):
...
I guess, to pass top and new as a parameter it should be something like:
path('posts/<ordering:top>/', posts, name='top'),
path('posts/<ordering:new>/', posts, name='new'),
But it gives me:
django.core.exceptions.ImproperlyConfigured: URL route 'posts/<ordering:top>/' uses invalid converter 'ordering'.
So, as a work around I use this, but it looks a little bit dirty:
path('posts/top/', posts, name='top', kwargs={'order': 'top'}),
path('posts/new/', posts, name='new', kwargs={'order': 'top'}),
What is the right way to do it?
You've misunderstood the way path converters work. The first element is the type, which here is str, and the second is the parameter name to use when calling the view. At this point you don't constrain the permissible values themselves. So your path would be:
path('posts/<str:ordering>/', posts, name='posts')
and when you come to reverse you would pass in the relevant parameter:
{% url 'posts' ordering='top' %}
If you really want to ensure that people can only pass those two values, you can either check it programmatically in the view, or you can use re_path to use regex in your path:
re_path(r'^posts/(?P<ordering>top|new)/$', posts, name='posts')

Django URLConf for former forum URL

I am tryimg to add content to a URL previously served by forum software. The URL is
/portal/forums/showthread.php?t=12345
I have this in my urlconf, but it's not working:
url("^portal/forums/showthread.php?t=12345", thread),
I am just matching the whole string to a single view for now, but a way to pass the topic ID as an argument would also be handy. (Hopefully all the old URLs similar enough to match, without any funky querystrings)
You need to access GET (Query string) parameters like this:
def myview(request):
t = request.GET.get('t')
#rest of the code.
The GET parameters should not be a part of the URL.
Your URL then would look like this:
url("^portal/forums/showthread.php", thread), #You might want the $ sign at the end.

how to "break" from a regex in django urlconf

I have the following views:
def tag_page(request, tag):
products = Product.objects.filter(tag=tag)
return render(request, 'shop/tag_page.html', {'products': products, 'tag': tag})
def product_page(request, slug):
product = Product.objects.get(slug=slug)
return render(request, 'shop/product_page.html', {'product': product})
along with the following url configurations:
url(r'^(?P<tag>.+)/$', 'tag_page'),
url(r'^(?P<tag>.+)/(?P<slug>[-\w]+)/$', 'product_page'),
The regex that has "tag" in it allows a url path to grow arbitrarily while sort of circularly redirecting to the tag_page view.
This lets me have the url: /mens/shirts/buttonups/, where all sections (/mens, /mens/shirts, /mens/shirts/buttonups/) of the path direct to the tag_page view, which is desired.
I want to end this behavior at some point however, and direct to a product_page view, which I attempt to accomplish with:
url(r'^(?P<tag>.+)/(?P<slug>[-\w]+)/$', 'product_page'),
When I follow a product_page link:
{{ product }}
I am directed to the tag_pag view. Presumably because that slug url matches the tag regex.
So the question: Is there a way I can keep the flexible tag regex redirect behavior but then "break" from it once I reach a product page? One important thing to note is that I want to keep the product page within the built up url scheme like: mens/shirts/buttonups/shirt-product/
Any insight is appreciated, Thanks!
Do you really need the forward slash on the end of the product page URL? A URL which ends with a forward slash is distinct from one which does not.
Just like delimiters are left at the end of a path to suggest a directory (with files underneath it) and left off at the end of file paths, so too could you leave the slash on for the tag sections but lop it off for individual products.
That gets around the problem entirely :-)
I think that you can't do it with just urlconf- .* always matches everything.
I would do that in this way:
url(r'^(?P<path>.+)/$', 'path_page'),
def path_page(request,path):
tags,unknown = path.rsplit('/',1)
try:
product = Product.objects.get(slug=unknown)
return some_view_function(request,path,product)
except Product.DoesNotExist:
return some_another_view_function(request,path)
But- I see here a few problems:
What if tag has the same name as product's slug?
Your solution is SEO unfriendly unless you want to bother with duplicate content meta tags

How to organize URLs in django for views handling GET data and parsing URL?

I have a view that displays some movie data. I thought that it might be a good idea to have a view handle a an URL like movie-id/1234 to search for movie id 1234. Furthermore I would like to be able to enter the ID into a form and send that to a server and search for it. To do that I created a second entry in the urls.py file shown below.
urlpatterns = patterns('',
url(r'movie-id/(?P<movie_id>.+?)/$', 'movieMan.views.detailMovie'),
url(r'movie-id/$', 'movieMan.views.detailMovie', name='movieMan.detailMovie.post'),
)
So if I want to pass data to my view either via a URL or a GET or POST request I have to enter two urls or is there a more elegant way? In the view's code I am then checking if there is any GET data in the incoming request.
To make the second url usable with the template engine, where I wanted to specify the view's url using the {% url movieMan.detailMovie.post %} syntax I had to introduce a name attribute on this url to distinguish between these two.
I am not sure if I am thinking too complicated here. I am now asking myself what is the first url entry good for? Is there a way to get the URL of a movie directly? When do these kinds of URLs come into play and how would they be generated in the template ?
Furthermore I would like to be able to enter the ID into a form and
send that to a server and search for it.
Is this actually a search? Because if you know the ID, and the ID is a part of the URL, you could just have a textbox where the user can write in the ID, and you do a redirect with javascript to the 'correct' URL. If the ID doesn't exist, the view should return a Http404.
If you mean an actual search, i.e. the user submitting a query string, you'll need some kind of list/result view, in which case you'll be generating all the links to the specific results, which you will be sure are correct.
I don't think there is a more elegant way.
I did almost the same thing:
url( r'^movies/search/((?P<query_string>[^/]+)/)?$', 'mediadb.views.search_movies' ),
The url pattern matches urls with or without a search parameter.
In the view-function, you will have to check whether the parameter was defined in the url or in the query string.

Django Generic object_list pagination. Adding instead of replacing arguments

I'm having some trouble with the django generic object_list function's pagination not really being "smart" enough to compensate my daftness.
I'm trying to do a url for listing with optional arguments for page number and category.
The url in urls.py looks like this:
url(r'^all/(?:(?P<category>[-\w]+)/page-(?P<urlpage>\d+))?/$',
views.listing,
),
The category and urlpage arguments are optional beacuse of the extra "(?: )?" around them and that works nicely.
views.listing is a wrapper function looking like this( i don't think this is where my problem occurs):
def listing(request,category="a-z",urlpage="1"):
extra_context_dict={}
if category=="a-z":
catqueryset=models.UserProfile.objects.all().order_by('user__username')
elif category=="z-a":
catqueryset=models.UserProfile.objects.all().order_by(-'user__username')
else:
extra_context_dict['error_message']='Unfortunately a sorting error occurred, content is listed in alphabetical order'
catqueryset=models.UserProfile.objects.all().order_by('user__username')
return object_list(
request,
queryset=catqueryset,
template_name='userlist.html',
page=urlpage,
paginate_by=10,
extra_context=extra_context_dict,
)
In my template userlist.html I have links looking like this (This is where I think the real problem lies):
{%if has_next%}
<a href=page-{{next}}>Next Page> ({{next}})</a>
{%else%}
Instead of replacing the page argument in my url the link adds another page argument to the url. The urls ends up looking like this "/all/a-z/page-1/page-2/
It's not really surprising that this is what happens, but not having page as an optional argument actually works and Django replaces the old page-part of the url.
I would prefer this DRYer (atleast I think so) solution, but can't seem to get it working.
Any tips how this could be solved with better urls.py or template tags would be very appreciated.
(also please excuse non-native english and on the fly translated code. Any feedback as to if this is a good or unwarranted Stack-overflow question is also gladly taken)
You're using relative URLs here - so it's not really anything to do with Django. You could replace your link with:
Next Page> ({{ next }})
and all would be well, except for the fact that you'd have a brittle link in your template, which would break as soon as you changed your urls.py, and it wouldn't work unless category happened to be a-z.
Instead, use Django's built-in url tag.
Next Page> ({{ next }})
To make that work, you'll have to pass your category into the extra_context_dict, which you create on the first line of your view code:
extra_context_dict = { 'category': category }
Is /all/a-z/page-1/page-2/ what appears in the source or where the link takes you to? My guess is that the string "page-2" is appended by the browser to the current URL. You should start with a URL with / in order to state a full path.
You should probably add the category into the extra_context and do:
next page ({{next}})
"Instead of replacing the page argument in my url the link adds another page argument to the url. The urls ends up looking like this "/all/a-z/page-1/page-2/"
that is because
'<a href=page-{{next}}>Next Page> ({{next}})</a>'
links to the page relative to the current url and the current url is already having /page-1/ in it.
i'm not sure how, not having page as an optional argument actually works and Django replaces the old page-part of the url
one thing i suggest is instead of defining relative url define absolute url
'Next Page> ({{ next }})'