django how to display a weeks data - django

Hi thanks for helping me
I being doing some browsing on google and stack overflow, but documentation django and python I can hardly understand, how the they make code run
I just can't figure out a way to display week data (table & chart) with
two toggle button to toggle different weeks of 53 weeks in a year
I had try using the week in Django template tags; https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#date
but I get empty value instead; here example I did {{ value|date:"W" }}
is there easily way to do this? I do not wish to use the weekarchiveview:
https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-date-based/#weekarchiveview
As I need to toggle between years,months and weeks on same page.
Below are my codes
this my code for views
from django.shortcuts import render
from django.views.generic import ListView, DetailView ,TemplateView
from zigview.models import tank_system
from django.utils import timezone
from datetime import date, timedelta
class EC(ListView):
model = tank_system
template_name = 'FrounterWeb/extends/EC.html'
ordering = ['-datetime'] # sort dates in descending order
def get_context_data(self, **kwargs):
return {'tank': self.get_queryset()}
This is my apps url codes
from django.urls import path
from . import views #function views
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required, permission_required
urlpatterns = [
path('',login_required(views.index.as_view()), name='index'), # views to call our index
path(r'', TemplateView.as_view(template_name='index.html'), name = 'myapp'), # tell django the which path to our main page
path(r'liveSterm/', login_required(views.Strem), name='Livesterm'), #call live strem page
path(r'EC-data/', login_required(views.EC.as_view()), name='EC'),
path(r'ph-data/', login_required(views.ph.as_view()), name='ph'),
path(r'Water-Temptures/', login_required(views.WT.as_view()), name='WT'),
path(r'Room-Temptures/', login_required(views.RT.as_view()), name= 'RT'),
path(r'Water-Flow-IN/', login_required(views.WaterFlowIN.as_view()), name= 'WFI'),
path(r'Water-Flow-OUT/', login_required(views.WaterFlowOUT.as_view()), name= 'WFO'),
]
this is my models codes
from django.db import models
from django.utils import timezone
from decimal import Decimal
# having errors KeyError: "'__name__' not in globals"
class tank_system(models.Model):
PH = models.DecimalField(max_digits=3, decimal_places=1)
EC = models.DecimalField(max_digits=3, decimal_places=1)
Winlet = models.DecimalField(max_digits=3, decimal_places=1)
Woutlet = models.DecimalField(max_digits=3, decimal_places=1)
WaterLevel = models.IntegerField(default=500)
TempWater = models.IntegerField(default=25)
TempRoom = models.IntegerField(default=25)
tanks = models.IntegerField(default=1)
datetime = models.DateTimeField(default=timezone.now())

You don't have 'value' in your context. The context is only 'tank'. So to get the datetime you can use {{ tank.datetime|date:"W" }}
To switch after clicking on a button you can write a simple piece of javascript that changes the inner html of a certain part of your DOM to {{ tank.datetime|date:"W" }} , {{ tank.datetime|date:"M" }} etc. after clicking the button

Related

Loggedin pages after authintification

I am learning django by myself and created mini project for learning pupose and as example took a kidgarden.
I have a directorry sun and with two apps inside it accounts and equity apps.
In accounts i have templates with login signup htmls. This section works fine without any problem.
Your directory structure is still not clear. Do this. If it's works, please comment and I will explain what was wrong in your code.
in main dictionary (sun) urls.py, copy and paste this code.
from django.contrib import admin
from django.urls import path,include
from . import views
from accounts import views as account_views # added line
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.HomePage.as_view(),name='home'),
path('accounts/',include('accounts.urls',namespace='accounts')),
path('accounts/',include('django.contrib.auth.urls')),
# path('kids/',views.TestPage.as_view(),name='kids'), # comment this url
path('kids/', account_views.home, name='kids'), # added url
path('thanks/',views.ThanksPage.as_view(),name='thanks'),
]
----- Edit ----
Initially, this was URL line. path('kids/',views.TestPage.as_view(),name='kids'). this was calling this function:
class ProductDetail(models.Model):
class TestPage(TemplateView):
template_name = 'equity/kids.html'
And your logic was written in this function (views in equity app):
def home(request):
stock = ChildForm()
if request.method == "POST":
stock = ChildForm(request.POST)
if stock.is_valid():
data = stock.save(commit=True)
name = data.name
context={
'name':name, }
else:
stock = ChildForm()
return render(request,'equity/kids.html',{'stock':stock})
return render(request,'equity/garden.html',context)
return render(request,'equity/kids.html',{'stock':stock)
You had to call right function which was in equity' views. So solution was this:
replace this path('kids/',views.TestPage.as_view(),name='kids')
with this:
path('kids/', account_views.home, name='kids')
importing views from equity is first thing.
from accounts import views as account_views

django test a templatetag which uses the request

I'm using a custom templatetag to calculate currency values, currency is chosen from a select element. when the user choose the currency he want work with I save the chosen currency in the session and refresh the page.
a templatetag shows the value calculated for the choosen currency.
in any template
{% load currency %}
{% set_currency request 156 %}
in my_app/templatetags/currency.py
from django.conf import settings
from djmoney_rates.utils import convert_money
register = template.Library()
#register.inclusion_tag('includes/price.html')
def set_currency(request, price):
# currency_session could be 'USD', 'EUR' ...
currency_session = request.session.get(settings.CURRENCY_SESSION_KEY, settings.DEFAULT_CURRENCY)
money = convert_money(price, settings.DEFAULT_CURRENCY, currency_session)
return {'amount': '%d' % money.amount, 'currency': money.currency}
includes/price.html is just
<span class="amount">{{amount}}</span>
<span class="currency">{{currency}}</span>
Now I'm wondering the way to test this templatetag, how to pass the request, and how make session to exists in that request.
I would only test the function.
from django.test import TestCase, RequestFactory
from django.conf import settings
from my_app.templatetags.currency import set_currency
class SetCurrencyTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_set_currency(self):
request = self.factory.get('/any/path/really/')
request.session = {
settings.CURRENCY_SESSION_KEY: settings.DEFAULT_CURRENCY
}
response = set_currency(request, 156)
self.assertEqual(response['amount'], 42)
self.assertEqual(response['currency'], 'BTC')
I'd also consider setting request.session without using settings, but that depends on your application.

Embedding Video File in Django Site

I have a Django site that I'm creating, and I want some of the pages to have videos embedded in them. These videos aren't part of a model. I just want to be able to use the view to figure out which video file to play, and then pass the file path into the template. All the files are hosted locally (for now, at least).
Is it possible to do with Django? And if so, how do I do it?
There are two ways you can do this -
Method 1: Pass parameter in URL and display video based on that parameter -
If you don't want to use models at any cost, use this, else try method 2.
Assuming you have saved all videos in your media directory and they all have unique names (serving as their ids).
your_app/urls.py -
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^video/(?P<vid>\w+)/$',views.display_video)
# \w will allow alphanumeric characters or string
]
Add this in the project's settings.py -
#Change this as per your liking
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
your_app/views.py -
from django.conf import settings
from django.shortcuts import render
from django.http import HttpResponse
import os
import fnmatch
def display_video(request,vid=None):
if vid is None:
return HttpResponse("No Video")
#Finding the name of video file with extension, use this if you have different extension of the videos
video_name = ""
for fname in os.listdir(settings.MEDIA_ROOT):
if fnmatch.fnmatch(fname, vid+".*"): #using pattern to find the video file with given id and any extension
video_name = fname
break
'''
If you have all the videos of same extension e.g. mp4, then instead of above code, you can just use -
video_name = vid+".mp4"
'''
#getting full url -
video_url = settings.MEDIA_URL+video_name
return render(request, "video_template.html", {"url":video_url})
Then in your template file, video_template.html, display video as -
<video width="400" controls>
<source src="{{url}}" type="video/mp4">
Your browser does not support HTML5 video.
</video>
Note: There can be performance issue, iterating through all the files in the folder using os.listdir(). Instead, if possible, use a common file extension or use the next method (strongly recommended).
Method 2 : Storing video ids and correspondig file names in database -
Use same settings.py, urls.py and video_template.html as in method 1.
your_app/models.py -
from django.db import models
class videos(models.Model):
video_id = models.CharField(blank=False, max_length=32)
file_name = models.CharField(blank=False, max_length=500)
def __str__(self):
return self.id
your_app/views.py -
from django.conf import settings
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import videos
def display_video(request,vid=None):
if vid is None:
return HttpResponse("No Video")
try:
video_object = get_object_or_404(videos, pk = vid)
except videos.DoesNotExist:
return HttpResponse("Id doesn't exists.")
file_name = video_object.file_name
#getting full url -
video_url = settings.MEDIA_URL+file_name
return render(request, "video_template.html", {"url":video_url})
So if you want to access any page with video id 97veqne0, just goto - localhost:8000/video/97veqne0

Django cms accessing extended property

I've extended the Django cms Page model into ExtendedPage model and added page_image to it.
How can I now acces the page_image property in a template.
I'd like to access the page_image property for every child object in a navigation menu... creating a menu with images...
I've extended the admin and I have the field available for editing (adding the picture)
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pagemodel import Page
from django.conf import settings
class ExtendedPage(models.Model):
page = models.OneToOneField(Page, unique=True, verbose_name=_("Page"), editable=False, related_name='extended_fields')
page_image = models.ImageField(upload_to=settings.MEDIA_ROOT, verbose_name=_("Page image"), blank=True)
Thank you!
BR
request.current_page.extended_fields.page_image
should work if you are using < 2.4. In 2.4 they introduced a new two page system (published/draft) so you might need
request.current_page.publisher_draft.extended_fields.page_image
I usually write some middleware or a template processor to handle this instead of doing it repetitively in the template. Something like:
class PageOptions(object):
def process_request(self, request):
request.options = dict()
if not request.options and request.current_page:
extended_fields = None
try:
extended_fields = request.current_page.extended_fields
except:
try:
custom_settings = request.current_page.publisher_draft.extended_fields
except:
pass
if extended_fields:
for field in extended_fields._meta.fields:
request.options[field.name] = getattr(extended_fields, field.name)
return None
will allow you to simply do {{ request.options.page_image }}

django-haystack 2.0.0beta facet example - not showing facet counts

I've been working through the documentation for Haystack 2.0.0beta, and using solr3.6.0 as my backend. I have gotten through the getting started example. Working with the facet example now.
search_indexes.py
import datetime
from haystack import indexes
from bsmain.models import Note
class NoteIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
author = indexes.CharField(model_attr='user', faceted=True)
pub_date = indexes.DateTimeField(model_attr='pub_date')
def get_model(self):
return Note
def index_queryset(self):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
urls.py
from django.conf.urls.defaults import *
from django.conf import settings
from django.conf.urls.defaults import *
from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView
sqs = SearchQuerySet().facet('author')
urlpatterns = patterns('haystack.views',
url(r'^$', FacetedSearchView(form_class=FacetedSearchForm,searchqueryset=sqs),
name='haystack_search'),
)
I have tested in python shell and get facets and counts, but when I fire the /search url (with the html provided in the example for facets) I get the form but no facets or counts.
Can anyone see anything wrong in the code above or is there somehing else I am missing?
Thanks.
Did you rebuild the index (./manage.py rebuild_index)?
Once done then create the schema.xml (./manage.py build_solr_scema > schema.xml)
Then copy the shcema.xml to your solr conf directory and restart the solr.
That should solve your problem.