I'm trying to add avatar support to my flask app but i've encountered an interesting bug:
Im using the same sub-templates for _post and _comment on both of my home and user pages with links to images in static/uploads folder but these images only show inside my home template:
sub-template _post.html
<table class="table table-bordered">
<tr style="border: solid; border-color: #1B1C1C; border-width: 2px;">
<td width="70x" style="background-color: #DEE1E1; border-right: 1px solid grey;">
<a href="{{ url_for('user', username=post.author.username) }}">
<img height="150px" width="150px" src='static/uploads/{{post.author.username}}.jpg'>
</a>
<!-- <img style="border-style: solid; border-radius: 10%; border-color: black; border-width: 1px; background-color: white;" src="{{ avatars.robohash(post.author.username, size='80') }}" /> -->
</td>
<td>
<p><a href="{{ url_for('user', username=post.author.username) }}">
{{ post.author.username }}
</a>said: </p> <p style="margin-left: 90%; margin-top: -2%;">..at {{post.timestamp.replace(microsecond=0)}}</p>
<p style="width: 60%;" id="post{{ post.id }}">{{ post.body }}</p>
<div class="button" style="margin-left: 95%; margin-top: -2%;">
{% if current_user.liked_post(post) %}
👎
{% else %}
👍
{% endif %}
</div>
<p style="width: 11%;">{{ post.likes.count() }}👍</p>
</td>
</tr>
</table>
{% for comment in comments %}
{% if comment in post.comments %}
{% include "_comment.html" %}
{% endif %}
{% endfor %}
<p style="margin-bottom: 4%; margin-top: 1%;"><a style="border: solid; border-radius: 4%; border-color: black; border-width: 1px;
padding: 10px; margin-left: 10px; margin-top: 10%;" href="/comment/{{post.id}}"> Post Comment ▲</a></p>
sub-template _comment.html
<table class="table table-bordered" style="border-left: 7px solid; border-color: #30F153">
<tr style="border: solid; border-color: grey; border-width: 2px;">
<td width="70x" style="background-color: #E8E8E8; border-right: 1px solid grey;">
<a href="{{ url_for('user', username=comment.commenter.username) }}">
<img height="100px" width="100px" src='static/uploads/{{comment.commenter.username}}.jpg'>
</a>
<!-- <img style="border-style: solid; border-radius: 10%; border-color: black; border-width: 1px; background-color: white;" src="{{ avatars.robohash(comment.commenter.username, size='40') }}" /> -->
</td>
<td>
<p><a href="{{ url_for('user', username=comment.commenter.username) }}">
{{ comment.commenter.username }}
</a>commented: </p> <p style="margin-left: 90%; margin-top: -2%;">..at {{comment.timestamp.replace(microsecond=0)}}</p>
<p style="width: 60%;">{{ comment.body }}</p>
<div class="button" style="margin-left: 95%; margin-top: -2%; margin-bottom: -10%;">
{% if current_user.liked_comment(comment) %}
👎
{% else %}
👍
{% endif %}
</div>
<p style="width: 11%;">{{ comment.comment_likes.count() }}👍</p>
</td>
</tr>
</table>
template user.html
{% extends "base.html" %}
{% block app_content %}
<table style="margin-top: 1%; ">
<tr valign="top" style="width: 100%;">
<td>
<img height="400px" width="400px" src="/static/uploads/{{user.username}}.jpg">
</td>
<td>
<h3 style="margin-left: 1%;">{{ user.username }}</h3>
{% if user.about_me %}<p style="margin-left: 2%; width: 470%;">About me: {{ user.about_me }}</p>{% endif %}
<p style="margin-left: 2%;">Followers: {{ user.followers.count() }} Following: {{ user.followed.count() }}</p>
{% if user == current_user %}
<p style="margin-left: 2%;"></p>
{% elif not current_user.is_following(user) %}
<p style="margin-left: 2%;">Follow</p>
{% else %}
<p style="margin-left: 2%;">Unfollow</p>
{% endif %}
</td>
</tr>
</table>
<div style="margin-top: 1%;">
{% for post in posts %}
{% include "_post.html" %}
{% endfor %}
</div>
{% endblock %}
template home.html
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block app_content %}
<h2>Hi, {{current_user.username}}</h2>
{% if form %}
{{ wtf.quick_form(form, button_map={'submit':'btn btn-outline-dark'}) }}
<br>
{% endif %}
{% for post in posts %}
{% include "_post.html" %}
{% endfor %}
{% endblock %}
my view functions:
# user page
#login_required
#app.route('/user/<username>')
def user(username):
if current_user.is_authenticated:
user = User.query.filter_by(username=username).first_or_404()
posts = user.posts.order_by(Post.timestamp.desc())
comments = Comment.query.all()
return render_template('user.html', title='User Page', user=user, username=current_user.username,
posts=posts, comments=comments)
return redirect(url_for('login'))
# home page
#login_required
#app.route('/', methods=['POST', 'GET'])
#app.route('/home', methods=['POST', 'GET'])
def home():
if current_user.is_authenticated:
form = PostForm()
if form.validate_on_submit():
post = Post(body=form.post.data, author=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been posted!')
return redirect(url_for('home'))
posts = Post.query.order_by(Post.timestamp.desc()).all()
comments = Comment.query.all()
return render_template('home.html', title='Home', form=form, username=current_user.username,
posts=posts, comments=comments)
return redirect(url_for('login'))
now for some reason when i look at the link to a post avatar from home page the path looks like this:
http://127.0.0.1:5000/static/uploads/image.jpg
and when im looking at an image from my user page it looks like this:
http://127.0.0.1:5000/user/static/uploads/SLDem.jpg
i'm guessing it has something to do with my route function having multiple sections but the avatar itself on the user page displays correctly..
You forgot a '/' in the _post.html and _comment.html in the img src. (?)
partials (post, comment)
<img height="150px" width="150px" src='static/uploads/{{post.author.username}}.jpg'>
user.html
<img height="400px" width="400px" src="/static/uploads/{{user.username}}.jpg">
url_for is also usable for static files:
{{ url_for('static', filename='css.css') }}
Link to Flask static files with url_for
Related
I'm new to web software programming and I'm facing a problem on how to update LED indicators on my Flask page.
I'm using an AJAX call to get the value of my python variable to my HTML. And I'm wondering if it's somehow possible to access the system_mode in AJAX call and put it in the if statement at the place of current_mode.
I know that I can display system_mode value in my HTML page by <div id="system_mode>, but I don't know how to get the value to put it in my if-statement.
I know that I can change the value of current_mode by using render_template in python code, but I don't want to refresh the webpage. That's why I have been using AJAX, as it updates the page continuously.
Python code:
mode = "startup"
#app.route('/update', methods = ['POST'])
def update():
return jsonify({
'system_mode': mode,
})
CSS code for one LED:
.led-green {
background-color: #94E185;
box-shadow: 0px 0px 4px 1px #94E185;
display: inline-block;
width: 20px;
height: 20px;
margin-right: 10px;
margin-left: 10px;
border: 1px solid #78D965;
border-radius: 20px;
}
.led-gray {
background-color: #c4c4c4;
box-shadow: 0px 0px 4px 1px #bdbdbd;
display: inline-block;
width: 20px;
height: 20px;
margin-right: 10px;
margin-left: 10px;
border: 1px solid #adadad;
border-radius: 20px;
}
HTML code:
!doctype html>
<html>
<head>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
>
<!-- Your file css -->
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='index.css') }}" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script>
setInterval(function() {
$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
console.log(response);
$("#system_mode").html(response["system_mode"]);
},
error: function(error) {
console.log(error);
}
})
}, 2000);
</script>
<div class="container my-5">
<div class="row">
<div class="col-sm-6 text-center my-3">
<h3>Status</h3>
<div class="row text-left my-3">
<div class="col">Startup</div>
<div class="col text-right">
{% if current_mode == "startup" %}
<div class="led-green"></div>
{% else %}
<div class="led-gray"></div>
{% endif %}
</div>
</div>
<div class="row text-left my-3">
<div class="col">Ready</div>
<div class="col text-right">
{% if current_mode == "ready" %}
<div class="led-green"></div>
{% else %}
<div class="led-gray"></div>
{% endif %}
</div>
</div>
<div class="row text-left my-3">
<div class="col">Warning</div>
<div class="col text-right">
{% if current_mode == "warning" %}
<div class="led-green"></div>
{% else %}
<div class="led-gray"></div>
{% endif %}
</div>
</div>
<div class="row text-left my-3">
<div class="col">Shutdown</div>
<div class="col text-right">
{% if current_mode == "shutdown" %}
<div class="led-green"></div>
{% else %}
<div class="led-gray"></div>
{% endif %}
</div>
</div>
<div class="row text-left my-3">
<div class="col">Sleeping</div>
<div class="col text-right">
{% if current_mode == "sleeping" %}
<div class="led-green"></div>
{% else %}
<div class="led-gray"></div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Thanks for any help! :)
Quick and dirty method (you need to specify the id of the html elem):
<div class="container my-5">
<div class="row">
<div class="col-sm-6 text-center my-3">
<h3>Status</h3>
<div class="row text-left my-3">
<div class="col">Startup</div>
<div class="col text-right">
{% if current_mode == "startup" %}
<div id="startup_id" class="led-green"></div>
{% else %}
<div id="startup_id" class="led-gray"></div>
{% endif %}
</div>
</div>
<div class="row text-left my-3">
<div class="col">Ready</div>
<div class="col text-right">
{% if current_mode == "ready" %}
<div id="ready_id" class="led-green"></div>
{% else %}
<div id="ready_id" class="led-gray"></div>
{% endif %}
</div>
</div>
<!-- continue -->
</div>
</div>
</div>
<script>
setInterval(function(){
$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
//parse your response to understand which html elements should be updated
system_mode = response["system_mode"];
//clear all html elem class with:
$("#startup_id").removeClass('led-green');
$("#startup_id").addClass('led-gray');
$("#ready_id").removeClass('led-green');
$("#ready_id").addClass('led-gray');
//continue...
if (system_mode == "startup") {
$("#startup_id").addClass('led-green');
} else if (system_mode == "ready"){
$("#ready_id").addClass('led-green');
} //continue...
},
error: function(error) {
console.log(error);
}
})}, 2000);
</script>
{% if current_mode %}
<div class="led-green"></div>
{% else %}
<div class="led-gray"></div>
{% endif %}
I am getting a problem in my project of college management system. I have tried to add an assignment submission functionality in my project. In which when a student clicks on an assignment created by teacher, it will lead him to a page which is : either submission page of assignment or if he had already submitted that assignment then update or only showing information about that.
urls.py file of project
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('cmsapp.urls')),
]
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py for cmsapp.
urlpatterns = [...
path('studentattendancereport', studentviews.student_attendance_report, name='studentattendancereport'),
path('fetchstudentattendance', studentviews.fetch_student_attendance, name='fetchstudentattendance'),
path('applyforleavestudent', studentviews.applyforleave, name='applyforleavestudent'),
path('marksreportstudent', studentviews.marksreportstudent, name='marksreportstudent'),
path('assignment', studentviews.assignments, name='assignment'),
path('assignmentupload/<int:id>', studentviews.assignment_upload, name='assignmentupload'),
]
views.py
def assignments(request):
subject = Subject.objects.filter(course=Student.objects.get(admin=request.user.id).course)
assignments = []
for s in subject:
for a in Assignment.objects.filter(subject_id=s.id):
assignments.append(a)
context = {'assignments': assignments}
return render(request, 'cmsapp/student/assignments.html', context)
def assignment_upload(request, id):
if request.method == 'POST':
student_id = Student.objects.get(admin=request.user.id)
assignment = Assignment.objects.get(id=id)
assignment_file = request.FILES['assignment']
try:
Student_Assignment.objects.create(assignment_id=assignment, student_id=student_id, document=assignment_file)
messages.success(request, 'Assignment is submited successfully.')
return redirect('assignment')
except:
messages.error(request, 'There is some problem, Please try again later.')
return redirect('assignment')
else:
assignment = Assignment.objects.get(id=id)
student_id = Student.objects.get(admin=request.user.id)
assignment_report = Student_Assignment.objects.filter(assignment_id=assignment.id, student_id=student_id).first()
if assignment_report:
context = {'assignment':assignment, 'assignment_report':assignment_report, 'student_id':student_id}
return render(request, 'cmsapp/student/assignment_report.html', context)
else:
context = {'assignment':assignment, 'assignment_report':assignment_report, 'student_id':student_id}
return render(request, 'cmsapp/student/assignment_upload.html', context)
assignment.html
<div class="container">
<h3 class="heading">Assignments
</h3>
<table class="table table-hover table-bordered mt-4">
<tr class="bg-dark text-white"><th>ID</th><th>Title</th><th>Description</th><th>Subject</th><th>Session</th><th>Created_at</th><th>Updated_at</th></tr>
{% for a in assignments %}
<tr>
<td>{{a.id}}</td>
<td>{{a.title}}</td>
<td>{{a.description}}</td>
<td>{{a.subject_id}}</td>
<td>{{a.session_id}}</td>
<td>{{a.created_at}}</td>
<td></td>
</tr>
{% endfor %}
</table>
</div>
assignment_upload.html
<div class="container">
<h3 class="heading">Assignment</h3>
<table class="table table-hover table-bordered text-capitalize">
<tr><th>Assignment Id</th><td>{{assignment.id}}</td></tr>
<tr><th>Title</th><td>{{assignment.title}}</td></tr>
<tr><th>Description</th><td>{{assignment.description}}</td></tr>
<form action="{% url 'assignmentupload' assignment.id %}" method="POST" class="form-group" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" placeholder="assignment" name="assignment" class="form-control mt-4">
<button class="btn btn-outline-success form-control mt-2">Submit</button>
</form>
</div>
assignment_report.html
<div class="container">
<h3 class="heading">Assignment</h3>
<table class="table table-hover table-bordered text-capitalize">
<tr><th>Assignment Id</th><td>{{assignment.id}}</td></tr>
<tr><th>Title</th><td>{{assignment.title}}</td></tr>
<tr><th>Description</th><td>{{assignment.description}}</td></tr>
<tr> <th>Your Assignment ID</th> <td>{{assignment_report.id}}</td></tr>
<tr> <th>Student ID</th> <td>{{assignment_report.student_id.id}}</td></tr>
<tr> <th>Document</th> <td>{{assignment_report.document}}</td></tr>
<tr> <th>Update</th> <td><form action="" method="POST" class="form-group" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" placeholder="assignment" name="assignment" class="form-control mt-1" style="width: 40%; display: inline;" accept=".pdf">
<button class="btn btn-outline-success btn-sm mt-2" style="display: inline; float: right; width: 20%;">Update</button>
</form></td></tr>
</table>
<a class="btn btn-outline-secondary btn-sm" href="{{assignment_report.document.url}}" open>Open</a>
<a class="btn btn-outline-info btn-sm" href="{{assignment_report.document.url}}" download>Download</a>
<p style="font-size: 12px; color: gray;">To Open or Download Assignment file click on buttons above.</p>
</div>
base.html
<div style="height: 120%; min-height: 96vh; display: flex; flex-wrap: wrap; align-content: stretch;">
<div class="container d-flex align-content-stretch flex-wrap float-left"
style="width: 15%;float: left; background-color: black;">
<nav class="nav nav-pills flex-column">
{% with request.resolver_match.url_name as url_name %}
<a class="nav-item nav-link nav-fill {% if url_name == 'studentdashboard'%}active{% endif %}"
href="{% url 'studentdashboard' %}">Dashboard</a>
<a class="nav-item nav-link subject {% if url_name == 'studentattendancereport'%}active{% endif %}"
href="#">Subjects</a>
{% for s in subject %}
<a class="nav-item nav-link d-none subject-token border border-dark {% if url_name == 'studentattendancereport'%}active{% endif %}"
href="#">{{s}}</a>
{% endfor %}
<a class=" nav-item nav-link {% if url_name == 'studentattendanceview'%}active{% endif %}"
href="studentattendancereport">Attendance</a>
<a class="nav-item nav-link {% if url_name == 'studentattendanceview'%}active{% endif %}"
href="marksreportstudent">Marks</a>
<a class="nav-item nav-link {% if url_name == 'assignment' or url_name == 'assignmentupload' %}active{% endif %}"
href="assignment">Assignment</a>
<a class="nav-item nav-link {% if url_name == 'applyforleave'%}active{% endif %}"
href="applyforleavestudent">Leave</a>
<a class="nav-item nav-link" href="#">Feedback</a>
{% endwith %}
<a class="nav-item nav-link" id="logout" href="{% url 'logout' %}">Log Out</a>
</nav>
</div>
<div style="background-color: white; width: 85%; float: right; height: 100%;">
{% if messages %}
<div class="messages container mt-2">
{% for message in messages %}
<div{% if message.tags %}
class="alert text-capitalize alert-{% if message.tags == 'error' %}danger{% else %}success{%endif%}"
{% endif %}>{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
<div style="width: 100%;margin-top: 5px;">
{% block content %}
{% endblock %}
</div>
</div>
</div>
I have similar type of url for update student details where it not throwing such wrong url.
In your base.html
When you set href for your <a> tags, make sure it is
href="{% url 'some-url-name' %}"
For example, what you have written
href="studentattendancereport"
this will just append that to your current url
You have to make that correct for
href="studentattendancereport" ---> href="{% url 'studentattendancereport' %}"
href="marksreportstudent" ---> href="{% url 'marksreportstudent' %}"
href="assignment" ---> href="{% url 'assignment' %}"
href="applyforleavestudent" ---> href="{% url 'applyforleavestudent' %}"
You can refer here to learn more about django's url template tag
I have a Django app where users can create their lists and add to-dos. I want to add a new page which will show to-dos that had due dates. Like, in the page, there will be a section called "Earlier" which was feature tasks with missed due dates. Other sections would be "Today", "Tomorrow" and "Later on". Let me show my view class and HTML code now and explain my problem.
Class based view to handle this page:
class ToDoNextUpView(LoginRequiredMixin, ListView):
model = ToDo
template_name = "ToDo/next_up.html"
ordering = ["-due_date"]
context_object_name = "todos"
def get_queryset(self):
query_set = []
for todo in ToDo.objects.filter(creator=self.request.user, is_checked=False):
if todo.due_date is not None:
query_set.append(todo)
return query_set
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
today = datetime.datetime.now(datetime.timezone.utc)
tomorrow = today + datetime.timedelta(days=1)
todos_earlier = []
todos_today = []
todos_tomorrow = []
todos_later = []
for todo in ToDo.objects.filter(creator=self.request.user, is_checked=False):
if todo.due_date is not None:
if todo.due_date.day == today.day and todo.due_date.month == today.month and todo.due_date.year == today.year:
todos_today.append(todo)
elif todo.due_date.day == tomorrow.day and todo.due_date.month == tomorrow.month and todo.due_date.year == tomorrow.year:
todos_tomorrow.append(todo)
elif todo.due_date < today:
todos_earlier.append(todo)
elif todo.due_date > tomorrow:
todos_later.append(todo)
context["todos_earlier"] = todos_earlier
context["todos_today"] = todos_today
context["todos_tomorrow"] = todos_tomorrow
context["todos_later"] = todos_later
return context
And this is next_up.html
{% extends "ToDo/base.html" %}
{% block content %}
{% load crispy_forms_tags %}
{% if todos_earlier %}
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">Earlier</h1></center>
<br>
{% for todo in todos_earlier %}
<article class="content-section">
<div class="media-body full-content">
<h2>
<button onclick="location.href='{% url 'todo-check' todo.pk %}'" class="btn btn-outline-success">
<i class="fa fa-check"></i>
</button>
<a style="overflow: hidden; text-overflow: ellipsis;" href="{% url 'todo-detailed' todo.title todo.pk %}" class="article-title"> {{ todo.title }}</a>
<button data-toggle="modal" data-target="#exampleModalCenter{{ todo.pk }}" style="float: right;" class="btn btn-outline-danger">
<i class="fas fa-trash"></i>
</button>
{% if not todo.important %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-secondary">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% else %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-warning">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% endif %}
</h2>
<h3 style="color:red">
Was due on: {{ todo.due_date|date:"F d" }}
</h3>
</div>
</article>
{% endfor %}
{% endif %}
{% if todos_today %}
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">For Today</h1></center>
<br>
{% for todo in todos_today %}
<article class="content-section">
<div class="media-body full-content">
<h2>
<button onclick="location.href='{% url 'todo-check' todo.pk %}'" class="btn btn-outline-success">
<i class="fa fa-check"></i>
</button>
<a style="overflow: hidden; text-overflow: ellipsis;" href="{% url 'todo-detailed' todo.title todo.pk %}" class="article-title"> {{ todo.title }}</a>
<button data-toggle="modal" data-target="#exampleModalCenter{{ todo.pk }}" style="float: right;" class="btn btn-outline-danger">
<i class="fas fa-trash"></i>
</button>
{% if not todo.important %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-secondary">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% else %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-warning">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% endif %}
</h2>
<h3 style="color:blue">
Due today
</h3>
</div>
</article>
{% endfor %}
{% endif %}
{% if todos_tomorrow %}
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">For Tomorrow</h1></center>
<br>
{% for todo in todos_tomorrow %}
<article class="content-section">
<div class="media-body full-content">
<h2>
<button onclick="location.href='{% url 'todo-check' todo.pk %}'" class="btn btn-outline-success">
<i class="fa fa-check"></i>
</button>
<a style="overflow: hidden; text-overflow: ellipsis;" href="{% url 'todo-detailed' todo.title todo.pk %}" class="article-title"> {{ todo.title }}</a>
<button data-toggle="modal" data-target="#exampleModalCenter{{ todo.pk }}" style="float: right;" class="btn btn-outline-danger">
<i class="fas fa-trash"></i>
</button>
{% if not todo.important %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-secondary">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% else %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-warning">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% endif %}
</h2>
<h3 style="color:green">
Due tomorrow
</h3>
</div>
</article>
{% endfor %}
{% endif %}
{% if todos_later %}
<br>
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">Coming up later</h1></center>
<br>
{% for todo in todos_later %}
<article class="content-section">
<div class="media-body full-content">
<h2>
<button onclick="location.href='{% url 'todo-check' todo.pk %}'" class="btn btn-outline-success">
<i class="fa fa-check"></i>
</button>
<a style="overflow: hidden; text-overflow: ellipsis;" href="{% url 'todo-detailed' todo.title todo.pk %}" class="article-title"> {{ todo.title }}</a>
<button data-toggle="modal" data-target="#exampleModalCenter{{ todo.pk }}" style="float: right;" class="btn btn-outline-danger">
<i class="fas fa-trash"></i>
</button>
{% if not todo.important %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-secondary">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% else %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-warning">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% endif %}
</h2>
<h3 style="color:seagreen">
Due on: {{ todo.due_date|date:"F d" }}
</h3>
</div>
</article>
{% endfor %}
{% endif %}
{% endblock content %}
As you can see, I have written almost the exact same HTML code for every one of those sections. Although this technically works but I would never be able to live with myself. I have to write those check buttons four times, star buttons four times and everything else four times. This cannot be good.
Also, in my View, I have made some sloppy coding where I checked the date, month and year which didn't seem right. But I am aware that checking only the day is not good since same days can of be different months. And to be clear, these are DateTime objects so I cannot just equal them since the precise seconds won't match. But I guess this could still be okay. My main question here is what changes should I bring about in my HTML and Python code so that I can display all the sections within a single for loop (or maybe nested loops but I don't want to four same code four times).
Thanks.
I believe you should use Django's built-in template tag include for each todo section and for those includes make a file for each one of them extending a base generic one with the shared logic.
Below i show a example that could be used, now instead of writing 4 times the code just edit todo_generic.html
next_up.html
{% extends "ToDo/base.html" %}
{% block content %}
{% load crispy_forms_tags %}
{% if todos_earlier %}
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">Earlier</h1></center>
<br>
{% include "todos_earlier.html" with todos=todos_earlier %}
{% endif %}
{% if todos_today %}
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">For Today</h1></center>
<br>
{% include "todos_today.html" with todos=todos_today %}
{% endif %}
{% if todos_tomorrow %}
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">For Tomorrow</h1></center>
<br>
{% include "todos_tomorrow.html" with todos=todos_tomorrow %}
{% endif %}
{% if todos_later %}
<br>
<center><h1 style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-size: 10ch; background-color: royalblue;">Coming up later</h1></center>
<br>
{% include "todos_later.html" with todos=todos_later %}
{% endif %}
{% endblock content %}
todo_generic.html
{% for todo in todos %}
<article class="content-section">
<div class="media-body full-content">
<h2>
<button onclick="location.href='{% url 'todo-check' todo.pk %}'" class="btn btn-outline-success">
<i class="fa fa-check"></i>
</button>
<a style="overflow: hidden; text-overflow: ellipsis;" href="{% url 'todo-detailed' todo.title todo.pk %}" class="article-title"> {{ todo.title }}</a>
<button data-toggle="modal" data-target="#exampleModalCenter{{ todo.pk }}" style="float: right;" class="btn btn-outline-danger">
<i class="fas fa-trash"></i>
</button>
{% if not todo.important %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-secondary">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% else %}
<button style="float: right; margin-right: 5px;" onclick="location.href='{% url 'todo-toggle-important' todo.pk %}'"
type="submit" class="btn btn-warning">
<span aria-hidden="true"><i class="fas fa-star"></i></span>
</button>
{% endif %}
</h2>
{% block due %}{% endblock %}
</div>
</article>
{% endfor %}
todos_earlier.html
{% extends "todo_generic.html" %}
{% block due %}
<h3 style="color:red">
Was due on: {{ todo.due_date|date:"F d" }}
</h3>
{% endblock due %}
todos_today.html
{% extends "todo_generic.html" %}
{% block due %}
<h3 style="color:blue">
Due today
</h3>
{% endblock due %}
todos_tomorrow.html
{% extends "todo_generic.html" %}
{% block due %}
<h3 style="color:green">
Due tomorrow
</h3>
{% endblock due %}
todos_later.html
{% extends "todo_generic.html" %}
{% block due %}
<h3 style="color:seagreen">
Due on: {{ todo.due_date|date:"F d" }}
</h3>
{% endblock due %}
I am trying to pass one parameter from text input form into my app.py but i got the following error message:
Method Not Allowed
The method is not allowed for the requested URL.
Herewith my app.py configuration:
#main_blueprint.route('/reports/daily_reports')
def downloadsss():
if request.method == 'GET':
daily_path = "./app/templates/Repo/DailyReports"
daily_listOfFiles = os.listdir(daily_path)
return render_template('main/DailyReports.html', len = len(daily_listOfFiles), daily_listOfFiles
= daily_listOfFiles)
elif request.method == 'POST' and 'download' in request.form:
download = request.form.get('download')
path = 'C:/Users/Ahmed Mustafa/FlaskProject/app/templates/Repo/DailyReports/' + download
return send_file(path, as_attachment=True)
and the following is my HTML code:
{% extends "main/main_base.html" %} {# main/main_base.html extends layout.html #}
{% block content %}
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
h2 {color: black; font-size: 20px; font-family: "Lucida Sans Unicode", "Lucida Grande", sans-
serif;}
th {vertical-align: top; align-items: center;}
table{align-items: center; }
</style>
<div class="jumbotron text-center">
<p><font size="6">This page is to show the Daily Reports list!</font></p>
<form method="post">
<input type="text" name="download" />
<input type="submit" value="Download" />
</form>
<!-- For loop logic of jinja template -->
<li class="list-group-item"><font size="6">
{% print('Total Number of Reports:'), len %}</font></li>
<div align="left" >
{%for i in range(0, len)%}
{% print('Report Number:'),[i+1] %}
<li class="list-group-item">
<a href="file:///C:/Users/Ahmed
Mustafa/FlaskProject/app/templates/static/DailyReports/{{daily_listOfFiles[i]}}">
{{daily_listOfFiles[i]}}</a>
<p> </p>
<h2></h2>
</li>
{% endfor %}
</div>
</div>
{% endblock %}
You need to allow for a POST request on your route by adding POST to the methods argument of the route:
#main_blueprint.route('/reports/daily_reports', methods=('GET', 'POST'))
I have written a view which takes input either from a form where you can post your data directly or you can upload a ".csv" file like this given below:
views.py
def Some_view(request):
if request.method == 'POST':
form = My_form(request.POST)
else:
request.method == 'POST' and request.FILES['myfile']
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'myapp/des.html')
return render(request, 'myapp/des.html', {'form': form})
html template: des.html is like this:
{% extends 'protocol/base.html' %}
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
{% block content %}
<body>
<div class="container">
<div style="width:30%">
<form action="/result_view/" method="post">
{%csrf_token%}
{% for error in form.non_field_errors %}
<div class="form-group has-errors text-danger small">
{{error}}
</div>
{% endfor %}
{% for field in form %}
<div class="form-group has-errors text-danger small">
{{field.errors}}
</div>
<div class="form-group has-errors text-danger small">
</div>
{% endfor %}
<div class="form-group">
{{form.AA}}
</div>
<div class="form-group">
<button class="btn btn-primary" style="width:100%; margin-bottom: 30px ">Submit</button>
</div>
<h2> or <h2>
<style type="text/css">
.button {
background-color: #ff9800; /* Green */
border: none;
color: black;
padding: 10px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 10px;
margin-bottom: 30px;
}
</style>
<form method="post" enctype="multipart/form-data">
<div class="heading">
</h4>
</div>
{% csrf_token %}
<input class="input" type="file" name="myfile">
<button class="button" type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p class="text" >File uploaded successfully. </p>
{% endif %}
</div>
</form>
</div>
</body>
</html>
{% endblock %}
forms.py
from django import forms
class My_form(forms.Form):
AA = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Ex.: ARNDCEQGHILKMFPSTWYV'}))
class Meta:
fields = ['AA']
The form is working fine but in my case upload method is not working, when I use to upload file method alone if works fine but with form method, it is not working please help me out in this regards thanks.
i think you need to change if condition sequence:
if request.method == 'POST' and request.FILES.get('myfile'):
# You code here
elif request.method == 'POST':