django template variable in <a> - python

How can i add a django template variable to href attribute of tag?something like this
{{meeting.meeting_url}}
meeting.url stores a link to another website such as google etc and it is saved in database
Thanks in advance

To render meeting.meeting_url in your template you need to pass the meeting object as argument of the render function in your view.
More about the render function here
Here's an example of what should be done:
from django.shortcuts import render
from .models import Meeting
def my_view(request):
# View code here...
context = {'meeting': Meeting.objects.first()} # first is an example, put whatever you want
return render(request, 'myapp/index.html', context)
You must make sure that your url (www.google.com) does start by a / because it would refer to the root url of your website (127.0.0.1:8000) which redirects you to 127.0.0.1:8000/meeting/meeting-info/www.google.com

Related

Control requests to view and template output in django

This is a view for get all the records in the EducationalRecord model:
def all_education_resume(request):
RESUME_INFO['view'] = 'education'
educations_resume = EducationalRecord.objects.all().order_by('-created_date')
template = 'resumes/all_resume.html'
context = {'educations_resume': educations_resume, 'resume_info': RESUME_INFO}
return render(request, template, context)
Now, if I want to write exactly this view for other models (like job resumes, research resumes , etc.),
I must another view one separately.
My question is:
How can I get a view for all these requests, so first check the URL of
the request and then do the relevant query? How can I control URL
requests in my views?
My other question is exactly the same as my first question,with this difference:
control view that must render in specific template.In other words,in
second question the ratio between the template and the view is instead
of the ratio of the view to the url or how to create a template for
multiple views (for example, for a variety of database resume
resumes, I have a template) and then, depending on which view render,
the template output is different.
I have implemented these two issues as follows:
I wrote a view for each of request!
In each view, I set the value of RESUME_INFO['view'], and then I've checked it in a template page and specified the corresponding template.
What is the best solution to these two questions?
How can I get a view for all these requests, so first check the URL of the request and then do the relevant query? How can I control URL requests in my views?
You can access request.path, or you can let the url(..)s pass a parameter with kwargs that holds a reference to the model for example, but this is usually bad design. Typically if you use different models, you will likely have to order these different as well, filter these differently, render these differently, etc. If not, then this typically indicates that something is wrong with the modeling.
You can however make use of class-based views [Django-doc], to remove as much boilerplate as posssible. Your view looks like a ListView [Django-doc], by using such view, and patching where necessary, we can omit most of the "boilerplate" code:
# app/views.py
from django.views.generic.list import ListView
class MyBaseListView(ListView):
resume_info = None
template = 'resumes/all_resume.html'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['resume_info'] = {'view': self.resume_info}
return context
In the individual listviews, you then only need to specify the resume_info and the model or queryset to render it with the 'all_resume.html' template, for example:
# app/views.py
# ...
class EducationalResumeView(MyBaseListView):
queryset = EducationalRecord.objects.order_by('-created_date')
resume_info = 'education'
class OtherModelView(MyBaseListView):
model = OtherModel
resume_info = 'other_info'
So we can here use inheritance to define common things only once, and use it in multiple views. In case we need to change something in a specific view, we can override it at that level.
In the urls.py, you define such view with the .as_view() method [Django-doc]. For example:
# app/urls.py
from django.urls import path
from app.views import EducationalResumeView, OtherModelView
urlpatterns = [
path('education/', EducationalResumeView.as_view()),
path('other/', OtherModelView.as_view()),
]

Django: dynamic template rendering

I'm working on a site that has some mostly static content that I still want to use Django template tags in. I don't want to have to write a view and add a urlconf entry for each URL, I just want to add templates to a specific folder and have them be rendered and accessible on the web. Is there already a project out there that does this?
Write a catch all view and resolve template dynamically:
from django.shortcuts import render_to_response
import django.template
import django.http
def view_template(request, template_name):
try:
return render_to_response(template_name)
except django.template.TemplateDoesNotExist:
raise django.http.Http404('No such file: %s' % template_name)
And in your url-conf add, towards the end:
url(r'^/(?P<template_name>[\w-]+\.html)$', view_template),

Django - CreateView form on existing view and url

I'm using django generic views in my project CRUD. The CreateView class uses the following url to work:
urls.py
url(r'^create', BookCreate.as_view(model=Books, template_name='Myproj/book_create.html'), name='book_create'),
If I go the www.mywebsite.com/create the form appears just how I wanted it.
My problem is that I want to incorporate the form on another page, that already has a url, a view and a template. The url is like the one bellow:
urls.py
url(r'^author/(?P<id>[0-9]{1,})/$', author_view_handler, name='author_view'),
How can I resolve this?
The CreateView uses a ModelForm. If you want to use it also, you need to create a a Book model form yourself, something like this:
from django.forms import ModelForm
class BookModelForm(ModelForm):
pass
And then instantiate it form=BookModelForm() and pass it to the context of your author_view_handler view.
However I am not really sure why you would want to do something like that...
Update: To pass it to your view, use
from django.shortcuts import render
def author_view_handler(request):
form = BookModelForm()
return render(request, 'author_view_handler.html', {"form": form},
The above just passes the form to the author_view_handler view and does not contain any form handling code.

How can I get Django to create a unique URL view and page for each URLField entered

I'm trying to create a small app in a django project where when a URL is inputted into the URLField form, then a separate page is created for each URL creating a sort of directory page for each link people submit. For example, if I enter the URL http://www.facebook.com/username1 or http://www.facebook.com/username2 I'd like django to create a new page at www.mysite.com/username1 and www.mysite.com/username2 respectively. What's the best way to go about this? Thanks in advance very much! Here is my basic code for the Form field:
class newlinkform(forms.ModelForm):
link_comment = forms.CharField(max_length=256) #comment to go along with URL entered
url = forms.URLField(max_length = 512) #actual submitted link I'd like to get a view mapped to
class Meta:
model = newlink
If you had something like this in your urls.py:
...
url(r'URL/^(?P<url_param>[a-zA-Z0-9_]*)/$', 'views.view_for_all_pages', name='view_for_all_pages')
...
Then your views.py could look like this:
from django.shortcuts import render as render_original
def view_for_all_pages ( request, url_param ):
render (request, "template.html", { "url_param" : url_param })
And your template:
<h1>URL entered: {{url_param}}</h1>
Then you could request: http://yourserver.com:8000/URL/foo to see <h1>URL entered: foo</h1>

Django Find Out if User is Authenticated in Custom Tag

I'm trying to create a custom tag. Inside this custom tag, I want to be able to have some logic that checks if the user is logged in, and then have the tag rendered accordingly. This is what I have:
def user_actions(context):
request = template.Variable('request').resolve(context)
return { 'auth': request['user'].is_athenticated() }
register.inclusion_tag('layout_elements/user_actions.html', takes_context=True)(user_actions)
When I run this, I get this error:
Caught VariableDoesNotExist while rendering: Failed lookup for key [request] in u'[{}]'
The view that renders this ends like this:
return render_to_response('start/home.html', {}, context_instance=RequestContext(request))
Why doesn't the tag get a RequestContext object instead of the Context object? How can I get the tag to receive the RequestContext instead of the Context?
EDIT:
Whether or not it's possible to get a RequestContext inside a custom tag, I'd still be interested to know the "correct" or best way to determine a user's authentication state from within the custom tag. If that's not possible, then perhaps that kind of logic belongs elsewhere? Where?
By default, an instance of django.template.Context is used in rendering templates, but you can override this in your view, either by passing a subclass of django.template.Context as the context_instance keyword argument to render_to_response, or by instantiating the subclass, and passing it directly to Template.render.
For convenience, Django provides a useful, pre-defined Context subclass: django.template.RequestContext. RequestContext looks in your settings file for a setting called TEMPLATE_CONTEXT_PROCESSORS, which should be a tuple of callable objects, each of which should return a dictionary; RequestContext will loop over each callable, call it, and add the key/value pairs from its returned dictionary to the template context as variables. Check out these links for a more detailed explanation.
To add the current user to your template context, you need django.core.context_processors.auth:
Add the django.core.context_processors.auth context
processor to your list of context
processors in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
... # Other context processors follow
)
Ensure the view than renders the template which calls
your custom tag uses RequestContext:
from django.template.context import RequestContext
from django.shortcuts import render_to_response
def my_view(request):
# Do some stuff
return render_to_response('templates/view.html',
context_instance=RequestContext(request))
Using RequestContext calls all context processors defined
in settings.TEMPLATE_CONTEXT_PROCESSORS, including the
auth context processor, which adds a context variable 'user'
to your template context.
In your template tag, you can access this variable
via context['user']
#register.inclusion_tag('templates/custom/tag.html', takes_context=True)
def custom_tag(context):
user = context['user']
if user.is_authenticated():
# Some stuff for the logged-in users
else:
# Stuff for anonymous users
i dont see how your view is linked to the template tag, because from what i know its django's template system that renders the tag, so the context is a dictionary, try this, hopefully it helps
user = context['user']
if user.is_authenticated():
do stuff
The "context" of a template node is a different thing to the RequestContext. A Context is also a dictionary, so if it has a user at all it would be accessed via context['user'].
The template nodes context contains information to help it render itself within the template, after doing some reading of the docs, I cannot find any way to access the RequestContext which would be associated with the request via the django.template.Context.
Moreover django.template.RequestContext extends from django.template.Context specifically in order to handle the added request object which would contain the user. So it is no surprise that Context would not have access to it.
See the source code of Context for proof.
How to get the user
After a bit of searching I found the django.template.resolve_variable method which can be used as follows:
from django.template import resolve_variable
user = resolve_variable('user', context)
Where context is a template context.
I ended up just passing the "user" parameter to the tag and using that to decide if the user was auth'd or not.

Categories

Resources