Pass context variables from two view functions to the same template - django

I trying to render values from two function to one html and I not sure how to perform this task.
I suppose to use "return render" in both function? and how should be in urls.py to read this both functions?
For now I have as is bellow and of course TopAlerts not returning anything. Any suggestions?
views.py
def OneWeekRequest(request):
#code here....
......
return render_to_response('weeklyreport.html',
{'n1week': n1week,
'g1week': g1week,
'fweeks': fweeks,
'g4weeks': g4weeks,
'form': form,
'start': start,
'end': end,
'wnumber': wnumber,
'speriod': selectedrange},
context_instance=RequestContext(request))
def TopAlerts(request):
#code here....
......
return render(request, 'weeklyreport.html', {'tops': tops})
urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'platforms.views.queryset'),
url(r'^weeklyreport/$', 'weeklyreport.views.OneWeekRequest'),
#url(r'^weeklyreport/', include('weeklyreport.urls')),

I created templatetag.py in templatetags
from django import template
from platforms.models import Platform, Event
register = template.Library()
#register.simple_tag
def top_alerts(top):
tops = Event.objects.filter(sourcetype_id__in=[1, 3],
status_id__in=[1,2,7,8],
event_datetime__range=('2014-04-07', '2014-04-13')
).exclude(service_id__in=[759, 7]
).values("event_datetime",
"platform__name",
"host__name","service__name",
"eventtype__name",
"status__name", "data")
return {'tops': tops}
and in my template.
{% load templatetag %}
and
{% top_alerts top %}
And is working fine, but i not entirely sure if this goes correct way with my project.

You can't return two views from one URL. A URL always points to one single view (although of course multiple URLs can point to the same view).
It sounds like your TopAlerts view should really be an inclusion tag.

Related

Rendering database objects in Django

This is a basic question but I can't figure out what I'm doing wrong...
I'm trying to render a detail view in my django site, but my calls to get the object are just failing or else not rendering.
Here is what I have:
views.py
from django.template import loader
from django.views.generic.base import TemplateView
from django.http import HttpResponse
from .models import user_profile
def detail(request, content_id):
template = loader.get_template('profiles/detail.html')
profile = user_profile.objects.get(pk=content_id)
context = {'profile': profile}
return HttpResponse(template.render(context, request))
Within the template, I have simply been testing the calls using:
<h1>{{ profile }}</h1>
<h1>{{ profile.name }}</h1>
This is my first time rendering this from scratch, I know I'm missing something dumb I just can't sort it. Thank you!
edit This current setup receives a 500 error. Without the get(pk) statement it loads, but doesn't show the variables, just the rest of my HTML.
upon request, here is the urls.py:
urlpatterns=[
path('<int:content_id>/', views.detail, name='detail'),
]
edit: solution Solved! Ends up there was an issue with the model where a migration was not properly performed and a column was read as missing.
Model was contained a column that was missing in the database. Even though it was not being called, it still resulted in an error when the model was referenced.

how to return multiple file html in render request django?

I would like to return multiple values in multiple html files in a django view
i tried that but it was a mistake
def my_view(request):
#bla bla bla...
context ={
'value_1':value,
#....
}
return render(request,{'file_1.html','file_2.html','file_2.html'},context)
I have already separated it into 3 different views but the problem is that they have the same source and if I separate them I had 4 min of execution time, then the best is to combine them
urls.py
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.values2, name='values1'),
path('value2/', views.values2, name='values2'),
]
from here you can call all html pages without giving load to server
You can achieve this by just simply using in built functionality.
def my_view(request):
...
context ={
'template1_context':value1,
'template2_context':value2,
'template3_context':value3,
}
return render(request,'main_template.html',context)
And in your main_template.html
{% include "template2.html" with template2_variable=template2_context %}
{% include "template3.html" with template3_variable=template3_context %}

Is there way a to pass URL values in html files in django templates using constant substitution?

This is Django problem. I am a newbie to this.
This is my url.py file
from django.urls import path
from splunkAutomation.logic.Constants import Constants
from . import views
app_name = 'splunkAutomation'
urlpatterns = [
path(Constants.URL_FOR_SEEING_ALL_SPLUNK_QUERIES,views.viewForSeeingAllSplunkQueries, name=Constants.NAME_OF_URL_FOR_SEEING_ALL_SPLUNK_QUERIES),
]
I want to be able to reference this name "Constants.NAME_OF_URL_FOR_SEEING_ALL_SPLUNK_QUERIES" in html template.
The following is the snippet from the html file
<ul class="actions">
<li>Check</li>
</ul>
Basically I want to use the constant substitution instead of {% url 'splunkAutomation:splunkQuerySpecific' query.id %}
Is there a way to use this ?
I you add a name to the path:
path(Constants.URL_FOR_SEEING_ALL_SPLUNK_QUERIES,views.viewForSeeingAllSplunkQueries, name="url_link"),
You can use it like this:
Check
If you want to have a dynamic url, you can do this (example for class based views):
urlpatterns = patterns('',
url(
regex=r'^(?P<webaddress>\w+)/$',
view=Mysite.as_view(),
),
)
And in your view you grap the parameter:
def dispatch(self, request, *args, **kwargs):
self.webaddress= kwargs.get('webaddress', '')
In your template you can then access the value with
{{ view.webaddress }}

Django: Using named urls in #login_required decorator

Most of views in my django app use #login_required decorator. Also, I have three different login urls. Views have corresponding login urls hardcoded into their #login_required decorators.
#login_required('myapp/logintype1'):
def usertype1_home(request):
# Further dode
# ...
#login_required('myapp/logintype2'):
def usertype2_home(request):
# Further code
# ...
Since the number of such views is quite large, whenever I change login url in urls.py I have to change login-url in all the decorators. I want to use something like {% urls 'urlpatter1' %} and {% urls 'urlpatter2' %}. Can I use reverse?
How I can use named url patterns instead of hard coding url patterns in #login_required decorator?
Somewhere in the top of views.py after import ... statements add something like this
login_type1 = reverse_lazy('urlpatter1') # or LOGIN_TYPE1
login_type2 = reverse_lazy('urlpatter2') # or LOGIN_TYPE2
And use these variables later
#login_required(login_url=login_type1)
...
UPDATE: reverse was replaced with reverse_lazy as #Alasdair suggested. See docs (2nd point).

Django: Model parameter in the URL template tag

I want to use the url template tag for my generic view.
I have been searching a lot about this and I didn't find what I want, but it seems a simple issue.
I will use the example that the Django book, Making a View Generic, has used:
# urls.py
from django.conf.urls.defaults import *
from mysite import models, views
urlpatterns = patterns('',
(r'^events/$', views.object_list, {'model': models.Event}),
(r'^blog/entries/$', views.object_list, {'model': models.BlogEntry}),
)
# views.py
from django.shortcuts import render
def object_list(request, model):
obj_list = model.objects.all()
template_name = 'mysite/%s_list.html' % model.__name__.lower()
return render(request, template_name, {'object_list': obj_list})
So, I have one view for two URLs, my question is: How can I use the django URL template tag for this two URLs?
I want to do something like this in the html template:
href={% url "mysite.views.object_list" model="Event" %}
href={% url "mysite.views.object_list" model="BlogEntry" %}
Thanks!
You need to define name for the url:
(r'^events/$', views.object_list, {'model': models.Event}, name='my_name'),
and use it instead of the view path:
href={% url "my_name" model="Event" %}