Django : go back to correct paginator page - python

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}}

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})

How to send url as slug field into url in Django

I have my urls.py as this:
from django.urls import path
from . import views
urlpatterns = [
path('link',views.get_text,name='text'),
path('link/<link>',views.show,name='show')
]
When I enter a url like http://127.0.0.1:8000/link/https://www.geeksforgeeks.org/gate-cs-notes-gq/, it is showing page not found as it is checking the / in the slug url. I am storing the url and other fields in database, so I want to retrieve the database objects using the url. How to do such that when I enter a url in the browser, it takes the entire url as link field in urls.py , so that I can retrieve the db objects from views.py in this way:
def show(request,link):
objs = Links.objects.filter(link=link).values()
return HttpResponse('link')
Pass the URL in the querystring of the requesting URL: http://127.0.0.1:8000/link/?link=https://www.geeksforgeeks.org/gate-cs-notes-gq/
The data from the querystring is available in the request.GET dictionary in your view
def link_view(request):
if 'link' in request.GET:
objs = Links.objects.filter(link=request.GET['link']).values()
return HttpResponse(...)
else:
# Handle no link provided (views.get_text)
Your url patterns then only need to define one path that handles both cases where a URL is provided or not
urlpatterns = [
path('link/', views.link_view, name='link_view'),
]
To redirect, you can use HttpResponseRedirect. It will redirect the url without specifying the view. It you write HttpResponseRedirect('/link'), it will redirect you to http://127.0.0.1:8000/link. Since you mentioned, redirect from another view, you do in this way:
def link_view(request):
if 'link' in request.GET:
objs = Links.objects.filter(link=request.GET['link']).values()
return HttpResponse(...)
else:
# do something when no link provided (views.get_text)
return HttpResponseRedirect('/link?'+str(link))#str(link) is the url you want to get

why django does not find the url?

I'm new to django, and I'm trying to access the following web page by clicking on "dataset celiac" and acces so to "celiac.html". On the html side, here is my code which corresponds to this part of the page where I click on "dataset celiac":
<div class="visit">dataset celiac</div>
Then, on the views.py side, here is the code corresponding to the view which is supposed to return the html page to celiac.html:
def CeliacView(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = forms.CeliacForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
columns = form.cleaned_data['columns']
algo = form.cleaned_data['algo']
if algo == "Logistic regression" and columns == 'CDR3_IMGT':
return render(request, 'data/cdr3.html', locals())
else:
tableData = get_table_data_to_representation()
context = {'form': forms.CeliacForm(), 'tableData': tableData}
return render(request, 'data/celiac.html', context)
And regarding the urls.py file here is my code:
app_name = 'data'
urlpatterns = [
path('datasets/', views.SetView, name='datasets'),
path('celiac/', views.CeliacView, name='celiac'),
]
Finally, here is what django shows me when I click on celiac dataset: Page not found (404)
Can someone tell me what could be the problem here please? why django does not find the correct url ?
Your href shouldn't be the filename, put the path where your url points you towards. For making it more dynamic, I'd suggest using the url tag. Like so:
<div class="visit">dataset celiac</div>

Django - calling function does not redirect

I want to redirect and return view after submiting form on my homepage. Unfortunately after POST nothing is happend.
My homepage:
def home(request):
if request.method == 'POST':
url = request.POST['url']
bokeh(request,url)
return render(request,'home.html')
def bokeh(request,url):
//my calculation logic
return render(request,'bokeh.html')
Of course I send other attributes like dictionaries etc, but it works fine when I hardcode my url in browser. After clicking submit on my form in my homepage nothing is happend.
EDIT
my bokeh function look like that:
def bokeh(request,url):
source = urllib.request.urlopen(url).read()
soup = bs.BeautifulSoup(source, 'lxml')
descrp = [description.text for description in soup.find_all('p', class_="commit-title")]
author = [author.text for author in soup.find_all('a', class_="commit-author")]
dict1 = dict(zip(descrp,author))
dict2 = dict(Counter(dict1.values()))
label = list(dict2.keys())
value = list(dict2.values())
plot = figure(title='Github Effort',x_range=label,y_range=(0,30), plot_width=400, plot_height=400)
plot.line(label,value,line_width = 2)
script,div = components(plot)
return render(request,'bokeh.html',{'script': script,'div': div})
and my urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^bokeh/(?P<url>\w+)/$',views.bokeh,name='bokeh',url='url'),
]
And at this moment I got TypeError: url() got an unexpected keyword argument 'url'
You did not return the result of the bokeh function:
def home(request):
if request.method == 'POST':
url = request.POST['url']
return bokeh(request,url)
return render(request,'home.html')
Note however that this is not redirecting, and therefore you do not implement the Post/Redirect/Get pattern [wiki]. In case of a successful POST request, it is usually a good idea to perform a redirect, to prevent a user from refreshing the page, making the same POST request. A POST request frequently has side effects, and therefore we want to omit that.
You better make use of the redirect(..) function [Django-doc] here:
from django.shortcuts import redirect
def home(request):
if request.method == 'POST':
url = request.POST['url']
return redirect('bokeh', url=url)
return render(request,'home.html')
You should not use a url=… in the url(..) function:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^bokeh/(?P<url>\w+)/$', views.bokeh, name='bokeh'),
]

Tag detail page with Django-taggit

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.

Categories