how can i build dynamic link in Django?
I have a blog and each post need to have a unique link.
content of blog's post must show on linked page.
I searched in google but i'm was a little confused.
Thanks
The answer involves setting a slug on your model instance, then referencing it within your URL, and then consuming it in your view in order to determine what blog post to pass into your context. Honestly, this is unfortunately a loaded question, but one that is gone over in pretty much any starter tutorial on Django.
Check out this video as it covers exactly what you're asking (he's building a blog).
https://www.youtube.com/watch?v=Bmvd1O5pNIY
The Answer is:
steps:
in views:
def article_content_view(request,article_id):
content = Article.objects.get(id=article_id).content
context = {
'content':content
}
return render(request,'article.html',context)
in urls:
path('article/<int:article_id>/', views.article_content_view,name= 'article_content'),
in template html file:
<a href="{% url 'article_content' article.article_id %}"</a>
and my problem solved by add an id for each post in view:
'article_id': article.pk
you can see my github repo for this project.
you can get a unique random URL by using
import uuid
x = uuid.uuid4().hex
get this link in localhost:8000/?url=x
in urls.py
add path in urlpatterns
path(<url>/,viewname)
Related
Our website is listing properties ads.
When a user publish an ad, I would like to redirect him to a "thank you" page. But inside this thank you page I would like to put a button with the link to the detailed view of the created ad.
I don't want to use "messages" framework because I need a dedicated page for tracking purpose.
How can I send the context (in this case the absolute url of the created object) to the "thank you" page?
It doesn't matter if the solution requires the use of a class based view or a function view.
Many thanks in advance !
I found a clean solution.
In my view I redirect to a success page and pass a parameter. In the urls.py I setup the path of the success page in order to take the parameter in the URL. Then I can use the data passed to the success page.
in views.py using class based views
def post(self, request):
my_param = my_param
return redirect('success', param=my_param)
in urls.py
urlpatterns = [
path('success/<str:param>/', Success.as_view(), name='success'),
]
Hope this will help. It seems basic but it took me some time to figure out what I was looking for :)
I can't find solution for inserting hyperlink into generated pdf from Django easy_pdf. Link is displayed on pdf but as text. How to make this link clickable?
part of template.html:
{{item.campaign_name}}
part of view.py:
from easy_pdf.rendering import render_to_pdf_response
return render_to_pdf_response(request, template_name, context)
campaign_url is in context dictictionary
Thank you for your time
I hope this helps you.
The url will depend on how you stored it in the database. If it is something like https://www.something.com you can use
if you decide to use django urls then something like
You might want to look at the django documentation for more clarity. Django documentation
So I am struggling a bit, with something that logically seems so simple but due to my limited understanding of Django I am not sure where to look and how to formulate a solution.
Basically I have a Blog app set up and it shows the complete(all the content including disqus discussion) latest post on the home page. The post has a further link to the posts own page as well. I have set up Disqus and need to get some key information to use for the disqus_url and disqus_identifier. I have set up the model as follows with a method for get_absolute_url as follows:
def get_absolute_url(self):
return reverse('blog.views.renderBlog',args=[str(self.id),str(self.slug)])
My view is set up as follows:
def renderBlog(request,postid=1,slug=None):
template = 'blog_home.html'
if(postid == 1 and slug == None):
post = Post.objects.latest('date_created')
else:
post = Post.objects.get(slug=slug, id=postid)
data = {
'post':post,
}
return render(request, template, data)
As you can see the view is set up to handle both URL's as follows:
url(r'^$', 'renderBlog', name='blogHome'),
url(r'^post/(?P<postid>\d{1,4})/(?P<slug>[\w-]+)/$', 'renderBlog', name='blogPostPage'),
In my template I am setting disqus_identifier = '{{ post.get_absolute_url }}' and I am hardcoding the domain portion in the meantime as disqus_url = 'http://127.0.0.1{{ post.get_absolute_url }}';.. Same goes for the comment count <a href="" data-disqus-identifier.
I dont like doing things in a hackish manner, what would be the best method for me to get the full absolute url. I have looked at request.get_absolute_uri but am not sure on how to actually use it to get what I want.
Thanks
The way I like to do it is configure a context_processor:
from django.contrib.sites.models import Site
def base_context_processor(request):
return {
'BASE_URL': "http://%s" % Site.objects.get_current().domain
}
# or if you don't want to use 'sites' app
return {
'BASE_URL': request.build_absolute_uri("/").rstrip("/")
}
in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'path.to.base_context_processor',
...
)
(In newer versions of Django, modify context_processors under TEMPLATES, OPTIONS instead.)
then in templates:
Object Name
Another solution would be to use request.build_absolute_uri(location), but then you would have to create a template tag that takes a request object and a location or an object that has get_absolute_uri method. Then you would be able to use it templates like that: {% get_full_uri request=request obj=post %}. Here is documentation on how to write custom tags.
This question is pretty old but I think its still relevant.
To get_absolute_url with domain in Django template you can do the following:
<li>Home</li>
First check if the request is https or not and then get the request of the host and pass the absolute url.
This way you will get full URL with domain in Django template.
I know the question is old, but I'm not sure the best answer provided is the correct one.
You should just use
as the Django docs point out.
https://docs.djangoproject.com/en/4.0/ref/models/instances/#get-absolute-url
The url provided comes with the domain as well.
Regards
I have a view (views.loaditems) which runs some algorithm and passes items to a template(product.html) where the items are loaded, and with each item, I have a "add_to_shortlist" link. On clicking this link, the item is added in the user's shortlist (for which I have a function). I want that on click, the page is not reloaded and has its items, but simply add that item to the user's shortlist. Also, where should I define this shortlist function?
I'm new to Django, and any help would be much appreciated. Thanks.
Update: Here's my code:
views.py
def loaditems(request):
#some code
ourdeals = SDeals.objects.filter(**{agestring3:0})
sorteddeals = ourdeals.order_by('-total_score')
user = request.user
context = {'deals': sorteddeals, 'sl_products':sl_products, 'user':user,}
template='index.html'
return render_to_response(template, context, context_instance=RequestContext(request))
def usersl(request, id, id2):
userslt = User_Shortlist.objects.filter(id__iexact=id)
products = SDeals.objects.filter(id__iexact=id2)
product = products[0]
if userslt:
userslt[0].sdeals.add(product)
sl = userslt[0].sdeals.all()
return render_to_response('slnew.html', {'sl':sl}, context_instance=RequestContext(request))
in my index.html I have:
<div class="slist"></div>
which in urls.py takes me to views.usersl:
url(r'^usersl/(?P<id>\d+)/(?P<id2>\d+)/$', views.usersl),
I don't want to go to slnew.html, instead be on index.html without reloading it, and on click 'slist', just run the function to add to shortlist.
In order to make changes on the server and in a page without navigating with the browser you need to look at JavaScript solutions. Read up about Ajax. In essence you need to use some JavaScript to send the update to the server, and to change the HTML.
JQuery is one popular library that will help you to do this. A more sophisticated example is AngularJS. On the Django side you'll write some views that handle these small update tasks used in the page. Libraries like Django REST framework or Django Slumber will help you with that.
I'm using django-cms with apphooks to display book detail information. I need the page with the app hook to accept a slug that specifies which book to display.
I created a page called 'books' and added the apphook 'BookDetailApp'.
Here's what my books.cms_app file looks like:
class BooksApp (CMSApp):
name = _('Book Detail Page Application')
urls = ['books.urls']
apphook_pool.register(BooksApp)
Here's what my books.urls looks like:
urlpatterns = patterns('',
url(r'^(?P<slug>[\w\-]+)?', BookDetailView.as_view(), name='book_detail'),
)
And here's what my books.views file looks like:
class BookDetailView (DetailView):
model = Book
template_name = 'layouts/book-detail.html'
context_object_name = 'book'
This all works fine when I go directly to book detail page.
So going to http://localhost:8000/books/the-book-slug/ works exactly how I want to.
The problem is that I need be able to link to specific book detail pages from promos on the home page and none of the expected methods are working for me.
Using the page_url template tag from django-cms doesn't work because it only accepts one argument, so i can't provide the slug needed to determine which book to display:
go
As expected this only redirects to http://localhost:8000/books/ which throws an error because the required slug was not included.
So my next options are to use the url template tag or defining an get_absolute_url() function on the model. Neither of these options work:
go
def get_absolute_url(self):
return reverse('book_detail', args=[self.slug])
These both result in a NoReverseMatch: Reverse for 'book_detail' not found error.
If I include the books.urls conf in my main url conf then it works. So it would appear that if the url is only being used by a cms apphook that it can't be reversed by django.
Including books.urls in my main urls seems like a dirty solution and I definitely do not want to hardcode the urls in the template or the get_absolute_url function. Neither of those solutions seems very 'pythonesque'.
Any suggestions?
EDIT:
Reverse works only if I use the language namespace. According to documentation specifying language namespace shouldn't be required.
>>> reverse('en:book_detail', args=[book.slug])
This was apparently due to our application having cms.middleware.multilingual.MultilingualURLMiddleware which then forced all {% url %} template tags and the reverse() function to require the language namespace.
Since our site is not localized, removing the middleware worked fine. The documentation didn't seem that clear to me on this and finally found the answer from another source.