Notification when a certain point in time is exceeded (Python) - python

I would like to create a To-Do list in which I can schedule date and time of each task. My goal is to get some sort of response whenever the supplied datetime is equal to the current time. For example I scheduled Do laundry for Monday at 6pm on a Saturday evening. Two days later (on Monday at 6pm) I would like to get a notification that I should Do laundry.
Notice that the key idea can be found in the index() function in views.py in the first rows including the if-statement.
Here is my code:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<int:aufgabenzettel_id>", views.details, name="details"),
path("add/", views.add, name="add"),
path("delete/<int:aufgabenzettel_id>", views.delete, name="delete"),
path("edit/<int:aufgabenzettel_id>", views.edit, name="edit"),
path("update/<int:aufgabenzettel_id>", views.update, name="update")
]
models.py
from django.db import models
# Create your models here.
class Aufgabenzettel(models.Model):
Aufgabeselbst = models.CharField(max_length=64)
Datum = models.DateTimeField(auto_now_add=True)
Geplant = models.DateTimeField(auto_now_add=False, auto_now=False)
def __str__(self):
return f"{self.Aufgabeselbst}"
views.py (the important part can be found in the index function in the first rows including the if-statement)
from django.db.models.fields import DateTimeField
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from datetime import datetime
from .models import Aufgabenzettel
# Create your views here.
def index(request):
now = datetime.now()
Aufgaben_items = Aufgabenzettel.objects.all().order_by("-Geplant") #arrange objects in the correct order
for Aufgabenzettel.Geplant in Aufgaben_items: #run through the loop and...
if Aufgabenzettel.Geplant == now: #...search for items in the database where the scheduled time ("Geplant") is equal to the current time
return render (request, "aufgabenzettel/add.html") #response in any way e.g. by returning the add.html
return render(request, "aufgabenzettel/index.html", {
"Aufgabenliste":Aufgabenzettel.objects.all(), #currently not used
"Aufgaben_items":Aufgaben_items
})
def details(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
creationDate = aufgabenzettel.Datum
dueDate = aufgabenzettel.Geplant
return render(request, "aufgabenzettel/details.html", {
"details":aufgabenzettel,
"creationDate": creationDate,
"dueDate":dueDate
})
def add(request):
addDatum = timezone.now()
if request.method == "POST":
Aufgabe = request.POST["Hinzufügen"]
geplantes_datum = request.POST["DatumFeld"]
Aufgabenzettel.objects.create(Aufgabeselbst=Aufgabe , Datum=addDatum, Geplant=geplantes_datum) #Aufgabenname und Aufgabendatum erstellen
return HttpResponseRedirect(reverse("index"))
return render(request, "aufgabenzettel/add.html")
def delete(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
aufgabenzettel.delete()
return HttpResponseRedirect(reverse("index"))
def edit(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
return render(request, "aufgabenzettel/edit.html", {
"details":aufgabenzettel
})
def update(request, aufgabenzettel_id):
if request.method == "POST":
Aufgabe = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
Aufgabe.Aufgabeselbst = request.POST["Bearbeiten"]
Aufgabe.save()
return HttpResponseRedirect(reverse("index"))
return render(request, "aufgabenzettel/edit.html")
index.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1 id="MeineAufgaben">Meine Aufgaben</h1>
<table>
{% for Aufgabeselbst in Aufgaben_items %}
<tr>
<td>
<a href="{% url 'details' Aufgabeselbst.id %}">
{{ Aufgabeselbst }}
</a>
</td>
<td>
<form action="{% url 'delete' Aufgabeselbst.id %}" method="post">
{% csrf_token %}
<button type="submit" id="löschenbtn">Löschen</button>
</form>
</td>
<td>
<form action="{% url 'edit' Aufgabeselbst.id %}" method="post">
{% csrf_token %}
<button type="submit" value="{{ details }}" class="bearbeitenbtn">Bearbeiten</button>
</form>
</td>
</tr>
{% endfor %}
</table>
<h2>
Neue Aufgabe erstellen
</h2>
{% endblock %}
add.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1>Füge eine neue Aufgabe hinzu!</h1>
<form action="{% url 'add' %}" method="post">
{% csrf_token %}
<input type="text" name="Hinzufügen" placeholder="Neue Aufgabe">
<input type="datetime-local" name="DatumFeld">
<button type="submit" id="Hinzufügen">Hinzufügen</button>
</form>
{% endblock %}
details.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1>{{ details }}</h1>
<h3>Erstellt: {{ creationDate }}</h3>
<h2>Geplant: {{ dueDate }}</h2>
Zurück zu Aufgabe
{% endblock %}
edit.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h2>Bearbeite deine Aufgabe "{{ details }}"</h2>
<form action="{% url 'update' details.id %}" method="post">
{% csrf_token %}
<input type="text" name="Bearbeiten" value="{{details}}">
<button type="submit" class="bearbeitenbtn">Bearbeiten</button>
</form>
Zurück zu Aufgabe
{% endblock %}
layout.html
{% load static %}
<!DOCTYPE html>
<html lang="de">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Aufgabenzettel</title>
<link rel="stylesheet" href="{% static '/css/main.css' %}">
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
I don't get an Error or anything but the code is not running as expected. I just want the index function to loop through each element in the database Aufgabenzettel in models.py and if it detects an element where the scheduled time corresponds with the current time some sort of action (in this case a redirect to add.html is ecpected) should happen. However I don't get any such response...
Like always, I appreciate every kind of solution or help!

You're comparing datetimes the wrong way and that is why your if condition is failing (Aufgabenzettel.Geplant == now) .
Try comparing them like this:
In [1]: from datetime import datetime
In [2]: past = datetime.now()
In [3]: present = datetime.now()
In [4]: present.strftime('%Y-%m-%d %H:%M:%S') == past.strftime('%Y-%m-%d
%H:%M:%S')
Out[17]: False
In [5]: present.strftime('%Y-%m-%d %H:%M') == past.strftime('%Y-%m-%d %H:%M')
Out[2]: True
Usually datetimes are compared after converting them to iso format. You can also use the function .isoformat() from timezone.
Picked it up from here: How to compare two Datetime field in Django

Related

Problem not display datetime field form in browser in django

What I can't see input datetime form.form django in my browser?
the program that I run in the browser,
The following code displayed instead of the input datetime
i have brought the codes of all the pages, please check
Thank you for your reply
forms.py
from django import forms
from django.contrib.auth.models import User
from datetime import datetime
class ExpenseForm (forms.Form):
text = forms.CharField(
widget=forms.TextInput(attrs={'placeholder':'توضیحات' ,'class':'form-control'}),
label='توضیحات',
)
date = forms.DateTimeField(
initial=datetime.now(),
widget=forms.DateTimeInput(attrs={ 'placeholder':'تاریخ' ,
'class':'form-control',
'type': 'datetime-local'}),
label='تاریخ',
)
amount = forms.IntegerField(
widget=forms.NumberInput(attrs={'placeholder':'مقدار' ,'class':'form-control'}),
label='مقدار'
)
view.py
#login_required()
def submit_expense(request):
expense_form = ExpenseForm(request.POST or None)
if expense_form.is_valid():
text = expense_form.cleaned_data.get('text')
date = expense_form.cleaned_data.get('date')
amount = expense_form.cleaned_data.get('amount')
Expense.objects.create(text=text , date=date , amount=amount , user_id=request.user.id)
return redirect('/submit/expense')
context ={
'expense_form':expense_form
}
return render(request,'hello.html',context)
hello.html
{% extends 'shared/_MainLayout.html' %}
{% load static %}
{% block content %}
<div class="login-form"><!--expense form-->
<div class="col-sm-4 col-sm-offset-1">
<div class="login-form"><!--expense form-->
<h2>پولهای خرج شده :</h2>
<form method="post" action="#">
{% csrf_token %}
{{ expense_form.text }}
{{ expense_form.amount }}
{{ expense_form.data }}
<button type="submit" class="btn btn-default">ثبت</button>
</form>
</div><!--/login form-->
</div>
{% endblock %}
please check the image to see my problem
browser page
you wrote {{ expense_form.data }} instead of {{ expense_form.date }}

Form post request running wrong view method on Django

I'm trying to clone the Instagram web page using Django(version-3.1).
My Django project has an app called 'post'.
One of its template I have a form which is posting a comment to a post. The form post request should call the path('add_comment/',views.add_comment,name='add_comment'), but It's calling path('<slug:slug>/',views.post_details,name='post_details'), instead. And raising DoesNotExist at /post/add_comment error. I added print() statement at the beginning of both add_comment() and post_details() methods to find out which is running when the request is made. I have no idea what I have done wrong.
The project GitHub link - https://github.com/mirasel/Instagram_Clone
the post_details.html template is -
{% extends 'base.html' %}
{% load static %}
{% block title %} post {% endblock %}
{% block profilephoto %} {{ propic.url }} {% endblock %}
{% block body %}
<div>
<div>
<img src="{{post.image.url}}" alt="post" height="250px" width="250px">
</div>
<div>
<a href="{% url 'instagram:profile' post.uploader %}">
<img src="{{uploader.profile_pic.url}}" alt="{{uploader}}" style="border-radius: 50%;" height="24px" width="24px">
{{ post.uploader }}
</a><br>
<p>{{ post.date_published.date }}</p>
</div>
<div>
<p>{{ post.caption }}</p>
</div>
<div>
<form action="{% url 'post:add_comment' %}" id="comment_form" method="POST">
{% csrf_token %}
<textarea name="comment" id="comment" cols="30" rows="1" placeholder="Write a comment..."></textarea>
<input type="hidden" name="slug" id="slug" value="{{post.slug}}">
<!-- <input type="submit" style="display: none;" name="submit"> -->
</form>
<script>
$(function(){
$("#comment").keypress(function (e) {
if(e.which == 13 && !e.shiftKey) {
$(this).closest("form").submit();
e.preventDefault();
}
});
});
</script>
{% endblock %}
the views.py -
from django.shortcuts import render,redirect
from instagram.views import get_nav_propic,get_profile_details
from .models import UserPost,PostComment,PostLike
from django.http import JsonResponse
def get_post_likes(post):
likes = PostLike.objects.filter(post=post)
total_likes = len(likes)
likers = []
for l in likes:
likers.append(get_profile_details(l.liker))
return {'likers':likers,'total_likes':total_likes}
def get_post_comments(post):
comments = PostComment.objects.filter(post=post)
total_comments = len(comments)
commenter = []
comment = []
for c in comments:
commenter.append(get_profile_details(c.commenter))
comment.append(c.comment)
postcomment = zip(commenter,comment)
return {'post_comment':postcomment,'total_comments':total_comments}
def upload_post(request):
if request.method == 'POST':
image = request.FILES['post_img']
caption = request.POST['caption']
uploader = request.user
UserPost.objects.create(uploader=uploader,image=image,caption=caption)
return redirect('instagram:feed')
else:
context = {
'propic' : get_nav_propic(request.user)
}
return render(request,'post/upload_post.html',context)
def post_details(request,slug):
print('I am here in post details')
post = UserPost.objects.get(slug=slug)
context = {
'propic' : get_nav_propic(request.user),
'post' : post,
'uploader' : get_profile_details(post.uploader),
'LIKES' : get_post_likes(post),
'COMMENTS' : get_post_comments(post),
}
return render(request,'post/post_details.html',context)
def add_comment(request):
print('I am here in add comment')
if request.method == 'POST':
post_slug = request.POST.get('slug')
post = UserPost.objects.get(slug=post_slug)
user = request.user
comment = request.POST.get('comment')
PostComment.objects.create(post=post,commenter=user,comment=comment)
return redirect('post:post_details',slug=post_slug)
the urls.py -
from django.urls import path
from . import views
app_name='post'
urlpatterns = [
path('upload_post/',views.upload_post,name='upload_post'),
path('<slug:slug>/',views.post_details,name='post_details'),
path('add_comment/',views.add_comment,name='add_comment'),
]
The error - Error page
Solved
I had to make the URL path of add_comment as following-
#previous one
path('add_comment/',views.add_comment,name='add_comment'),
#modified one
path('comment/add_comment/',views.add_comment,name='add_comment'),
This is because the pattern for the slug URL and add comment URL were similar.
Because Django will process the urlpatterns sequentially, from docs:
Django runs through each URL pattern, in order, and stops at the first
one that matches the requested URL, matching against path_info.
And '/add_comment' is a valid slug <slug:slug>, so post_details will be called.
So you should keep the definition of the most generic url patterns at last:
urlpatterns = [
path('upload_post/',views.upload_post,name='upload_post'),
path('add_comment/',views.add_comment,name='add_comment'),
path('<slug:slug>/',views.post_details,name='post_details'),
]
Hopefully this will work for you.

HTML form data not posting to url but shows up in django model

brand new to django and webapps here.
I am experimenting with models and forms, and I have been able to successfully post data to my site using text fields and input buttons.
My hang is that my second form does not post anything and does not throw an error either.
I queried the class CustID and the set came back with all the data I had posted.
Here is the code and HTML:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Input</title>
</head>
<body>
<h1>Subscription Update</h1>
<h2></h2>
<form action="/addID/" method="post">{% csrf_token %}
<input type="text" name="content"/>
<input type="submit" value="Add"/>
</form>
<form action="/getCust/" method="post">{% csrf_token %}
<input type="text" name="cid"/>
<input type="submit" value="Customer Look Up"/>
</form>
<ul>
{% for SubID_item in all_items %}
<li>{{ SubID_item.content }}
<form action="/deleteID/{{SubID_item.id}}/"
style="display: inline;"
method="post">{% csrf_token %}
<input type="submit" value="Delete"/>
</form>
</li>
{% endfor %}
</ul>
</body>
</html>
Model:
from django.db import models
# Create your models here.
class SubID(models.Model):
content = models.TextField()
class CustID(models.Model):
cid = models.TextField()
views:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import SubID, CustID
import stripe
import json
# Create your views here.
def StrpFormView(request):
all_subid_items = SubID.objects.all()
return render(request, 'STRP_FORM.html',
{'all_items': all_subid_items})
def addID(request):
new_item = SubID(content=request.POST['content'])
new_item.save()
return HttpResponseRedirect('/STRP_Input/')
def getCust(request):
new_item = CustID(cid=request.POST['cid'])
new_item.save()
return HttpResponseRedirect('/STRP_Input/')
def deleteID(request, SubID_id):
del_items = SubID.objects.get(id=SubID_id)
del_items.delete()
return HttpResponseRedirect('/STRP_Input/')
def basere(request):
return HttpResponseRedirect('/STRP_Input/')
urls:
from django.contrib import admin
from django.urls import path
from STRP_FORM.views import StrpFormView, addID, deleteID, getCust, basere
urlpatterns = [
path('admin/', admin.site.urls),
path('STRP_Input/', StrpFormView),
path('addID/', addID),
path('deleteID/<int:SubID_id>/', deleteID),
path('getCust/', getCust),
path('', basere),
]
Thanks for taking the time to help me out!
NEW CODE:
def StrpFormView(request):
all_subid_items = SubID.objects.all()
all_custid_items = CustID.objects.all()
return render(request, 'STRP_FORM.html',
{'sub_items': all_subid_items},
{'cust_items': all_custid_items})
<ul>
{% for CustID_item in cust_item %}
<li>{{ cust_item.cid }}</li>
{% endfor %}
</ul>

I can't do delete button to run delete() in db query in django. Help anything does not work

I can't do delete button in django_tables2. I think i try everything from google and does not work :/ i try generic views and another and nothing.
In python script this work, but in the view of app not.
Could you watch my code and tell me what i did wrong?
urls.py
from django.conf.urls import url
from . import views
app_name = 'carslist'
urlpatterns = [
url('', views.carslist, name='carslist'),
url(r'^delete-entry/(?P<pk>\.*)/$', views.DeleteView.as_view(),
name='delete_view'),
]
views.py
def carslist(request):
fleets = Fleet.objects.all()
fleetTable = FleetTable(fleets, prefix='u_')
RequestConfig(request, paginate=False).configure(fleetTable)
payload = {
'fleetTable': fleetTable,
}
return render(request, 'carslist/car-list.html', payload)
class DeleteView(SuccessMessageMixin, DeleteView):
model = Fleet
success_url = '/'
success_message = "deleted..."
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
id = self.object.id
request.session['id'] = id # name will be change according to your need
message = request.session['id'] + ' deleted successfully'
messages.success(self.request, message)
return super(DeleteView, self).delete(request, *args, **kwargs)
I try with code like:
def delete(request, record_id):
row = Fleet.objects.filter(id=record_id)
row.delete()
and doesnt work too :(
tables.py
import django_tables2 as tables
from django_tables2 import TemplateColumn
from regcar.models import Car, Brand, Fleet
class FleetTable(tables.Table):
producent = tables.Column(accessor='car.brand',
verbose_name='Producent')
class Meta:
model = Fleet
attrs = {'class': 'table table-sm'}
sequence = ('id', 'producent', 'car', 'rok_produkcji',
'rodzaj_paliwa', 'pojemność_silnika_w_cm3', 'km',
'numer_rejestracyjny', 'vin', 'vat', 'leasing',
'przebieg','delete')
delete = TemplateColumn(template_name='pages/tables/button-
delete.html', verbose_name='')
cars-list-html
{% extends "base_car.html" %}
{% load django_tables2 %}
{% block head %}
{% load static %}e
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<script
src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js">
</script>
<script
src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js">
</script>
<script src="{% static "datatable/js/datatableview.min.js" %}"></script>
<script>
datatableview.auto_initialize = false;
$(function () {
var xeditable_options = {};
datatableview.initialize($('.datatable'), {
fnRowCallback: datatableview.make_xeditable(xeditable_options),
});
})
</script>
{% endblock %}
{% block login-div %}
<table>
<tr>
<th>
<a class="btn btn-outline-success btn-sm" href="{% url
'dashboard:dashboard' %}" role="button"
style="margin-right: 30px;">Dashboard</a>
</th>
<th></th>
<th>Hi {{ user.username }}!
<p>logout</p></th>
</tr>
</table>
{% endblock %}
{% block content2 %}
<h2>List of yours cars<br/></h2>
<hr style="border-top: 1px solid #aaaaaa">
{% render_table fleetTable %}
{% endblock %}
button
<form action="{% url 'carslist:delete_view' pk=part.pk %}" method="POST">
{% csrf_token %}
<input class="btn btn-default btn-danger" type="submit"
value="Delete"/>
</form>

Displaying form content instead of form object name

I am new to Django and I am trying to create a form in a template. I think I have accomplished this however I a missing a piece. This is what I currently see:
I think I am missing something from my form class that should display the choices.
forms.py
from django import forms
class TestForm(forms.Form):
one = forms.ChoiceField(choices=('HDFS', 'HDFS'), widget=forms.RadioSelect())
two = forms.ChoiceField(choices=('HIVE', 'HIVE'), widget=forms.RadioSelect())
three = forms.ChoiceField(choices=('BOTH', 'Both of HDFS and HIVE'), widget=forms.RadioSelect())
beatle = [one, two, three]
event_textarea = forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event_textarea'})
views.py
def home(request):
if request == 'POST':
# create a form instane and populate it with data from the request
form = TestForm(request.POST)
if form.is_valid():
# process the data in form.cleaned_data as required
form.cleaned_data()
# redirect to a new URL:
return HttpResponseRedirect('/test/')
# if a GET (or any other method) we'll create a blank form
else:
form = TestForm()
return render(request, 'home/home_page.html', {'form': form})
template:
{% extends 'index/index.html' %}
{% load staticfiles %}
{% block head %}
<script type="text/javascript" src="{{ STATIC_URL }}home/js/home.js" async></script>
<link href="{{ STATIC_URL }}home/css/home.css" rel="stylesheet">
{% endblock head %}
{% block content %}
<div>Welcome to Trinity E2E testing</div>
<form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
{% csrf_token %}
{% for radio in form.beatle %}
<div class="btn btn-default btn-lg">
{{ radio }}
</div>
{% endfor %}
{{ form.event_textarea }}
<input id="submit-test" type="submit" class="btn btn-default btn-lg" value="Submit">
</form>
{% endblock content %}
beatle list contains references to class attributes, not instance attributes.
How about make it a instance method to return instance attributes (form fields):
def beatle(self):
return [self.one, self.two, self.three]
UPDATE
To correctly return bound fields:
def beatle(self):
return [self['one'], self['two'], self['three']]
or
def beatle(self):
return [self[name] for name in ['one', 'two', 'three']]

Categories

Resources