Tag detail page with Django-taggit - python

Im trying to create pages for tags on my django blog. I already have a simple index page which displays a list of all used tags, now I want to have individual pages for each tag and on that page I will display all posts marked with that tag. The url structure for these tag detail pages will be like this
localhost/tag/my-tag-here
I already have django-taggit installed and added some tags and I have them displaying fine on post detail pages and the tag index page mentioned above but Im getting a 404 when I try to visit each tag detail page such as /tag/test.
These are my files and the full error message below.
views.py
def tag_detail(request, tag):
tag = get_object_or_404(Tag, tag=tag.name)
return render(request, 'blog/tags_detail.html', {'tag': tag})
urls.py (app)
urlpatterns = [
url(r'^$', views.blog_index, name='blog_index'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$',
views.blog_post_detail,
name='blog_post_detail'),
url(r'^contact/$', views.contact_form, name='contact_form'),
url(r'^thanks/$', views.thanks_view, name='thanks_view' ),
url(r'^about/$', views.about, name='about'),
url(r'^upload/$', views.upload_image, name='upload_image'),
url(r'^tag/(?P<tag>[-/w]+)/$', views.tag_detail, name='tag_detail'),
url(r'^tags/$', views.tags_index, name='tags_index')
]
and this is the full error message
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/tag/test
is the problem here in my view or the url structure? For the view I'm not 100% sure if thats the correct way to do it but Ive tried to do it the same as my post detail view.
thanks

The problem is in your views.py file.
In this code:
def tag_detail(request, tag):
tag = get_object_or_404(Tag, tag=tag.name)
return render(request, 'blog/tags_detail.html', {'tag': tag})
Here you wrote :
tag = get_object_or_404(Tag, tag=tag.name)
you passed a tag in URL so correct method would be :
tag = get_object_or_404(Tag, tag=tag)
But this will work only if, in your model,you have returned name of the tag as Unicode,Like this:
class Tag(models.Model):
name = models.CharField()
def __unicode__(self):
return unicode(self.name)
And if this still does not work then there might be a problem in TEPLATE_DIR setting in settings.py file. Then you have to share settings.py code for project file structure.

Related

Server not found when redirect tinyurl to original url, only slug isshown in the address bar

I am trying to create short urls for products. The short urls are generated and rendered successfully to the templates.
After I got my short URL, i copied it and search it in the browser, It says Server Not Found.
I want to redirect those short urls to original urls
For ex: My original url is - 127.0.0.1:8000/affiliation/link/10002/,
and its own short url is - tinyurl.com/yze3sjse; when i copy short url and search it on the browser, only the slug part is shown in the browser, i.e. affiliation/link/10002/ and Hence , it cannot redirect to original url
This is my functions :
Views.py
#Display individual product and render short links for all using pyshorteners
def link_view(request, uid):
results = AffProduct.objects.get(uid=uid)
slink = request.get_full_path()
shortener = pyshorteners.Shortener()
short_link = shortener.tinyurl.short(slink)
return render(request, 'link.html', {"results": results, "short_link": short_link})
Urls.py
urlpatterns = [
path('link/', views.link, name='link'),
path('link/<int:uid>/', views.link_view, name='link_view')
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also the address bar in the browser shows: 'affiliation/link/10004/', the localhost has been missed out
Your last sentence say everything.
You are trying to access to affiliation/link/10004/ which doesn't exist.
You forget to put the DNS/IP (in your case: localhost), like: http://mywebsite.com/affiliation/link/10004/
For me, the issue come from request.get_full_path() which only return the URL content, not the full address.
Below Function converts the URL to desired short links as you need:
#Display individual product and render short links for all using pyshorteners
def link_view(request, user_id, uid):
user_id = user_id
results = AffProduct.objects.get(uid=uid)
slink = "http://127.0.0.1:8000/" + request.get_full_path()
shortener = pyshorteners.Shortener()
short_link = shortener.tinyurl.short(slink)
return render(request, 'link.html', {"results": results, "short_link": short_link, "user_id": user_id})

Django : go back to correct paginator page

I have simple blog app that is using paginator for listing articles.
I want to be able to add button in article detail page that will direct user to same page that this article is on.
I want to take slug from current url and send it to paginator so that it directs user to ?page=X where article is on.
I checked paginator docs and didn't find any info on how to retrieve page number of specific object.
my views:
def blog(request):
posts = Article.objects.all()
paginator = Paginator(posts, 3)
page = request.GET.get('page')
posts = paginator.get_page(page)
return render(request,'blog.html',{'posts':posts})
def article_id(request,slug):
articleid = Article.objects.get(slug=slug)
return render(request, 'blogid.html', {'article':articleid})
my urls:
urlpatterns = [
url(r'^$', views.blog, name = 'blog'),
url(r'^(?P<slug>[\w-]+)/$', views.article_id, name = 'article_id'),
]
You can get the position of the object via
position=Article.objects.filter(your_filter_key=your_filter_value).order_by('other_filter_order').count()
Then get the page number via
items_per_page=yout_items_per_page
page = int(position/items_per_page)
Solved with help of Giancarlo's answer.
I added below to article_id
def article_id(request,slug):
articleid = Article.objects.get(slug=slug)
position = Article.objects.filter(date__gt=articleid.date).count()
page = str(int((position)/3)+1)
return render(request, 'blogid.html', {'article':articleid, 'page':page})
And then in template link looks like /blog/?page={{page}}

why do my django urls render the wrong template?

I'm suprised that I cannot access my product detail page through the url and I don't understand why since I've already done this basic thing plenty of times...
I have a page where all my products are displayed, when the user click on a product he is redirected to the product detail, that's it.
Somehow when I click a link linked to the product detail or type de correct path to the url it loads the same page where all the product are shown but it doesn't even call the product detail view, why so ?
Here are the views :
def rcdex(request):
list = Liste.objects.all()
return render(request, 'rcdex.html', {'list':list,})
def rc_detail(request, id):
list = Liste.objects.get(id=id)
return render(request, 'rc_detail.html', {'list':list,})
Here are the urls :
url(r'^', views.rcdex, name="rcdex"),
url(r'^rc/(?P<id>\d+)/$', views.rc_detail, name='rc_detail'),
Here is how I call the rc_detail view on the template :
<th>{{ l.entreprise }}</th>
I don't get why it doesn't show me the correct template (rc_detail.html) but instead reload rcdex.html ?
You haven't terminated your rcdex urlpattern, so it matches everything. You should use a $:
url(r'^$', views.rcdex, name="rcdex"),
you can also do like this..
url(r'^rc/(?P<id>\d+)/$', views.rc_detail, name='rc_detail'),
url(r'^', views.rcdex, name="rcdex"),

Django admin - add custom link to change list view

Firstly thanks for taking the time to read my problem
I tried to add a custom button to my admin changeList view, but it always gives me Page not found (404)
This my modelAdmin code:
class MyModelAdmin(admin.ModelAdmin):
class Media:
js = ('admin/js/additional_js.js',)
model = MyModel
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
analyze_url = patterns('',
(r'^(?P<pk>\d+)/analyze/$',
self.admin_site.admin_view(self.analyze_view))
)
return analyze_url + urls
def analyze_view(self, request, pk):
# some code here
HttpResponseRedirect(
reverse('admin:myapp_MyModel_change', args=(pk,))
)
My jQuery code for adding custom link to change list view:
(function($) {
$(document).ready(function($) {
$(".object-tools").append('<li>Analyze</li>');
});
})(django.jQuery);
when I click my custom link it gives me this:
MyModel object with primary key '3/change/analyze' does not exist.
I see that the link does not point to the view
Can someone help me fix this issue.
Thanks
In Django 1.9, the admin change url has changed to /admin/<app>/<model>/<pk>/change/ (release notes).
Therefore, it doesn't make sense to link to href="analyze/" in your html. The relative url is treated as /admin/<app>/<model>/3/change/analyze, not /admin/<app>/<model>/3/analyze as you expect.
You can probably fix the problem by changing the link to:
<a href="../analyze/" ...
Ideally, it would be better to reverse the url rather than having a relative link. I think this would make the code less fragile.
Since you are using Django 1.9, you can update your code to use a list rather than patterns:
from django.conf.urls import url
analyze_url = [
url(r'^(?P<pk>\d+)/analyze/$', self.admin_site.admin_view(self.analyze_view)),
]

Redirection is leading me to Page not found error in Django

Project urls.py includes app urls. I am using HttpResponseRedirect to get Likes posted on site. I am not trying to call for template so this is why not using render_to_response. My app view is:
def like_article(request, article_id):
if article_id:
a = Article.objects.get(id=article_id)
count = a.likes
count += 1
a.likes = count
a.save()
return HttpResponseRedirect('articles/get/%s' % article_id)
My app urls.py reflects likes redirection like this:
url(r'^like/(?P<article_id>\d+)/$', 'article.views.like_article'),
My parent "articles" HTML file extended from base says:
<p>{{article.likes}} people liked this article</p>
My single article page extended from base.html shows:
<p>Like</p>
Please advise.
You'd better use {% url [name] [parameters] %} in your template while reverse function in your view to create urls.
In your question, I think the problem is the url router doesn't match.
See:
<p>Like</p>
And:
url(r'^like/(?P<article_id>\d+)/$', 'article.views.like_article'),
It seemed the /article prefix doesn't appeared in you url.
Have you mapped the url - articles/get/article_id, i.,e added a similar pattern in urlpatterns (ex: url(r'^get/(?P<article_id>\d+)/$', 'article.views.get_article', name='get_article'),) tuple, to which you redirected the users!
If yes, then have you created a proper view for it!

Categories