what i am trying to do is:
Admin uploads a PDF file from admin panel. (1)
It needs to go to the specified template. (2)
And it should be downloaded by pressing download button in the template.
So here are codes:
(1)
class Reports(models.Model):
name = models.CharField(max_length=100, null=False, blank=False, verbose_name="File Name")
report = models.FileField()
(2)
<tr>
<td>"File Name must be showed in here"</td>
<td class="text-center">PDF</td>
<td class="text-center lang-tr-src"><i class="fas fa-file-download"></i></td>
<td class="text-center lang-en-src"><i class="fas fa-file-download"></i></td>
</tr>
In the website there will be one report for every month. I want to list them in the template and make them downloadable.
Should i write a view for that(if yes how it should be?) or what should i do?
Every single data you want to show to your template you need write it in your views.py, so this case is so specefic.
views.py:
def your_view_name(request):
reports = Reports.objects.all()
context = {
'reports': reports
}
return render(request, 'your_template.html', context)
Then make a url for your view in urls.py
urlpatterns = [
path("", views.your_view_name, name='your_url_name')
]
Your template:
<tr>
{% for obj in reports %}
<td>{{ obj.name }}</td>
<td class="text-center">PDF</td>
<td class="text-center lang-tr-src"><a href="{{ obj.report.url }}" Download
target="_blank"><i class="fas fa-file-download"></i></a></td>
<td class="text-center lang-en-src"><a href="" target="_blank"><i
class="fas fa-file-download"></i></a></td>
{% endfor %}
</tr>
create a new view firstly.
def report_view(request):
context = {}
reports= Reports.objects.all()
context['reports'] = reports
return render(request, "pages/report.html", context)
create an url for this view in urls.py
path('reports', report_view, name='report_view'),
in your template create forloop for this context like below:
{% for report in reports %}
<tr>
<td>"File Name must be showed in here"</td>
<td class="text-center">PDF</td>
<td class="text-center lang-tr-src"><i class="fas fa-file-download"></i></td>
<td class="text-center lang-en-src"><i class="fas fa-file-download"></i></td>
</tr>
{% endfor %}
Related
I have User default Django User model to register user. I want to print user last_login and join_date on the template. And also I want to check if user is active or not.
I want to check user active status like this, If user is currently using my website the status should be "Active" If User logged out Then status should be "Loged out"
if it is possible please provide me solution for this as well
accounts/models.py
class Profile(models.Model):
user = models.OneToOneField(User, default="1", on_delete=models.CASCADE)
image = models.ImageField(upload_to="images/", default="default/user.png")
def __str__(self):
return f'{self.user} profile'
dashboard/views.py (to display user data)
def admin_home(request):
data = Profile.objects.filter(Q(user__is_superuser=False), Q(
user__is_staff=False)).order_by('-user__last_login')[:10]
context = {
'data': data,
}
return render(request, "instructor/admin_home.html", context)
Accounts/urls.py
from django.contrib import admin
from . import views
from django.contrib.auth import views as auth_views
from django.urls import path
app_name="accounts"
urlpatterns=[
path('register',views.register,name="register"),
path('admin_login',views.admin_login,name="admin_login"),
path('user_login',views.user_login,name="user_login"),
path('admin_editprofile',views.admin_editprofile, name="admin_editprofile"),
path('user_editprofile',views.user_editprofile, name="user_editprofile"),
path('admin_profile',views.admin_profile, name="admin_profile"),
path('user_profile',views.user_profile, name="user_profile"),
path('Logout',views.Logout, name="Logout"),
path('user_chage_password' , views.user_chage_password , name="user_chage_password"),
path('admin_change_password',views.admin_change_password,name="admin_change_password"),
]
Extra I have two apps one is the dashboard and other accounts. In the accounts app I am implementing only accounts' related URLs and in the dashboard app I am using it for other things.
For user registration, I am using the Django's default User model.
show_all_users.html or template file (for displaying user's data)
<html lang="en" class="no-focus">
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'js/plugins/datatables/dataTables.bootstrap4.min.css' %}">
<link rel="stylesheet" id="css-main" href="{% static 'css1/codebase.min.css' %}">
</head>
<body>
<div id="page-container" class="sidebar-o sidebar-inverse side-scroll page-header-fixed main-content-narrow">
{% include "instructor/sidebar.html" %}
{% include "instructor/admin_nav.html" %}
<!-- Main Container -->
<main id="main-container" style="background-color:white;">
<!-- Page Content -->
<div class="content">
<div class=" container mt-5" style=" position: absolute; margin-left:-4%;">
<div>
<h1 class="text-success text-center"></h1>
<h4 class="text-center text-danger">Recently Logged in users</h4>
<table id="datatable" class="table table-striped table-bordered" style="width:100% color:gray;" >
<thead style="background-color : #607d8b;">
<tr>
<th scope="col">ID</th>
<th scope="col">Profile</th><th scope="col">Username</th>
<th scope="col">Last_login</th>
<th scope="col">join_date</th>
<th scope="col">Action</th>
</tr></thead>
<tbody>
{% for userData in data %}
<tr>
<th scope="row">{{userData.id}}</th>
<td><img style="width: 40px; border-radius:15px;" src="{{userData.image.url}}" alt="this is it."></td>
<td>{{userData.user.username}}</td>
<td> {{request.user.profile.date_joined }}</td>
<td>{{ request.user.profile.last_login }} </td>
<td>
<button class="btn btn-danger btn-sm" onclick="window.mytest()">Delete</button>
<script type="text/javascript">window.mytest = function() { var isValid = confirm('Are you sure to Delete this user?');
if (!isValid) { event.preventDefault(); alert("It wont delete. Yay!");}}</script>
</td>
</tr>
{% endfor %} </tbody></table></div>
</div>
</main>
{% endblock body %}
But this <td> {{request.user.profile.date_joined }}</td> line prints login date of currently logged in user but I want to show all user's last_login date.
And this <td>{{ request.user.profile.last_login }} </td> line prints nothing.
You can filter those users which have logged in at least one time through Q(user__last_login__isnull=False).
Try this query in the view:
views.py
def admin_home(request):
data = Profile.objects.filter(Q(user__is_superuser=False), Q(
user__is_staff=False), Q(user__last_login__isnull=False)).order_by('-user__last_login')[:10]
context = {
'data': data,
}
return render(request, "instructor/admin_home.html", context)
Issue:
Only last_login and date_joined are the valid fields in default User model of django.
Don't use request.user....., since it prints the details of current logged in users, as you stated that I want it to display for all users.
Question 1: But this <td> {{request.user.profile.date_joined }}</td> line prints login date of currently logged in user but I want to show all user's last_login date.
Answer: This is because request... give you current logged in user's details not all users' details.
Question 2: And this <td>{{ request.user.profile.last_login }} </td> line prints nothing.
Answer: It is because, there is wrong relationship of models.
Solution:
Try below code in template file for displaying all users:
<td> {{userData.user.last_login }}</td>
<td>{{ userData.user.date_joined }} </td>
Instead of this code you've tried:
<td> {{request.user.profile.date_joined }}</td>
<td>{{ request.user.profile.last_login }} </td>
Remember: Here, you have filtered only those users which are not staff as well as superuser, so these users are normal users. And if last_login column prints None that means the user has not logged even single time. And for date_joined,by default current time is taken by django. And if you see another time than your local machine that means you haven't set time zone in TIME_ZONE in settings.py. The timezone for India is Asia/kolkata, for more info refer Time zones[django-doc].
create signals.py and add this snippet:
from django.contrib.auth.signals import user_logged_in,user_logged_out
from datetime import datetime
#receiver(user_logged_in)
def user_logged(sender,request,user,**kwargs):
user.profile.last_login = datetime.now()
user.profile.save()
add the related_name attribute to your user field below your Profile model:
class Profile(models.Model):
user = models.OneToOneField(User,default="1", on_delete=models.CASCADE, related_name="profile")
image = models.ImageField(upload_to="images",default="default/user.png")
date_joined = models.DateTimeField()
def save(self, *args, **kwargs) -> None:
self.date_joined = datetime.now()
return super().save(*args, **kwargs)
def __str__(self):
return f'{self.user} profile'
run on terminal:
python manage.py makemigrations
python manage.py migrate
the official documentation
Hello I have an app that displays some database information in a table. Inside of the html template I am making an edit link that I want to open another app(page viewLit) while passing a value to it's view. I have added my code below. My question is I am unsure of how to make this links url and pass the object data located inside circuit.circuitid along with it. I haven't been able to find the right way to code this yet and this is just how I thought that this should be done. If anyone has a better idea I am open to suggestions.
search_custom.html(code for link)
{% for circuit in filter.qs %}
<tr>
<td class="actions">
View
</td>
<td>{{ circuit.circuitid }}</td>
</tr>
{% endfor %}
myapp/myapp/urls.py
urlpatterns = [
path('viewLit/', include('viewLit.urls')),
]
myapp/viewLit/urls.py
urlpatterns=[
path('viewLit/circuitid.id', views.viewLit, name='viewLit'),
]
myapp/viewLit/views.py
def viewLit(request, circuitid):
#display records fields here
return HttpResponse("You are at the viewLit page!")
Have a look at the documentation:
Django documentation
myapp/viewLit/urls.py
urlpatterns=[
path('viewLit/(?P<circuit_id>\w+)', views.viewLit, name='viewLit'),
]
html- template:
search_custom.html(code for link)
{% for circuit in filter.qs %}
<tr>
<td class="actions">
View
</td>
<td>{{ circuit.circuitid }}</td>
</tr>
{% endfor %}
So I have a django DetailView that I can easily render by getting all the data that I need from get_context_data in my class based view. But the problem is that each time to render this template I would need to choose a date in this template, get the date somehow and then re-render that same template from the date picked.
I've been googling how to make this happen, there are something I could maybe do with AJAX, but maybe there is something easier to try, because I have little to no experience with AJAX/JS stuff
class PlaceDetailView(LoginRequiredMixin, PermissionCheckMixin, PlaceViewMixin, DetailView):
template_name = "places/place_detail.html"
def get_context_data(self, **kwargs):
context = super(PlaceDetailView, self).get_context_data(**kwargs)
place = context.get("object")
contract = Contract.objects.filter(pk=place.id).first()
context["renter"] = User.objects.filter(pk=contract.renter_id).first()
now = timezone.now()
meters = MeterInstallation.objects.filter(places=place.id)
context["active_meters"] = meters.filter(active_until__gte=now)
context["old_meters"] = meters.filter(active_until__lt=now)
context["services"] = ServiceTask.objects.filter(place=place)
# Need to add more context values from more models, but the date has to be given, how?
return context
place_detail_view = PlaceDetailView.as_view()
<div class="tab-pane fade show active" id="values" role="tabpanel" aria-labelledby="values-tab">
{% if values %}
<div class="table-responsive-sm">
<table class="table small">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Values</th>
</tr>
</thead>
<tbody>
{% for value in values %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<!-- todo add needed values (type, values from/to, diff, tariff, total_price) -->
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
No values.
{% endif %}
</div>
I would like to know is there an option to re-render this template when a date is being picked? Or maybe there is a better option to make this happen?:)
I hope someone can give me a little help on how to do the following with Django (excuse me if I don't explain everything correct, still new to Django and don't know about a lot of things) :
I have a table of Movies, those Movies have a "Description" Datafield, where when they click on it a form opens up with the current description of the movie. If they double click on this description they are allowed to change it and then save the value. I've made a small gif to visualize the idea:
At least thats the basic Idea behind this, so far I've managed to make most of the things run, but sadly not the Django part where the "new" data from the user is send to the Databank and replaces the old data of the Description.
So could someone explain to me how I can make that work? I know that I'd probably have to write a function to my views.py and then create a new url pattern, but I just can't figure out how exactly. So any help is welcome! Below is my code (I hope I've included every file you guys need):
views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.views.generic.list import ListView
from .models import *
class AllMovies(generic.ListView):
model = Movie
template_name = "consilium/index.html"
context_object_name = "latest_movie_list"
class MovieDetails(generic.DetailView):
model = Movie
template_name = "consilium/detail.html"
urls.py
from django.conf.urls import url
from . import views
from .models import *
from django.views.generic.list import ListView
app_name = "consilium"
urlpatterns = [
url(r'^$', views.AllMovies.as_view(), name="index"),
url(r'^(?P<slug>[\w_0-9]+)/$', views.MovieDetails.as_view(), name='detail'),
]
models.py
from django.db import models
from decimal import Decimal
from django import forms
from django.contrib import admin
class Movie(models.Model):
// removed the other models for better overview
description = models.TextField('Movie Description')
def __str__(self):
return self.title
index.html
{% extends "consilium/base.html" %}
{% block body %}
<table class="table">
<thead>
<tr>
<th></th>
<th colspan="2">My Movielist</th>
<th>
</tr>
<tr>
<th></th>
<th>TITLE</th>
<th>GENRE</th>
<th>RELEASE DATE</th>
<th>DIRECTOR</th>
<th>DESCRIPTION</th>
<th>RUNTIME</th>
<th>STATUS</th>
<th>IMDB</th>
</tr>
</thead>
<tbody>
{% if latest_movie_list %}
{% for movie in latest_movie_list %}
<tr>
<td></td>
<td>
<a href="{% url 'consilium:detail' movie.slug %}" data-toggle="popover" data-placement="left" data-content='<img class="title-image" src="{{movie.image.url}}"/>'>{{ movie.title }}</a>
</td>
<td>{{ movie.get_genre_display}}</td>
<td>{{ movie.date}}</td>
<td>{{ movie.director}}</td>
<td id="icn-change" data-toggle="collapse" data-target=".demo{{ forloop.counter }}">
Description <i class="fa fa-caret-right"></i>
</td>
<td>{{ movie.runtime}} min</td>
<td>{{ movie.get_status_display}}</td>
<td>{{ movie.imdb}}</td>
</tr>
<tr>
<td></td>
<td class="hiddenRow" colspan="8">
<div class="container collapse demo{{ forloop.counter }}">
<div class="row justify-content-center">
<div class="col">
<form method="post" id="usrform">{% csrf_token %}
<textarea id="text" class ="form-control" readonly="true" onkeydown="expandtext(this)" ondblclick="this.readOnly='';">{{movie.description}}</textarea>
</form>
</div>
</div>
<div class="row justify-content-center">
<div class="col align-self-start">Double Click to Edit</div>
<div class="col align-self-end">
<input type="submit" id="set" class="pull-right"/>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td>No Movies are available.</td>
</tr>
{% endif %}
</tbody>
</table>
{% endblock %}
script.js
// removed all other code for overview
// replace description text with user input
$('#set').click(function() {
var test = $('#text').val();
localStorage.setItem("test", test);
});
$('#text').text(localStorage.getItem("test"));
I hope I didn't miss anything, thanks for everyone who can help me!
I worked on a similar project, and here is what I did.
from django.forms.models import model_to_dict
#login_required
def edit_profile(request):
profile, created = ClientProfile.objects.get_or_create(user_id=request.user.id)
if request.method == 'POST':
form = ProfileSubmissionForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('jobs:list'))
else:
profile_dict = model_to_dict(profile)
form = ProfileSubmissionForm(profile_dict)
return render(request, 'jobs/profile.html', {'form': form})
Essentially, the model_to_dict renders the values stored in the database in the form. The instance=profile makes sure I'm updating the form and not creating a new object.
Figured it out thanks to the great help of the pythondev slack community!
views.py: getting the description field of my Movie Model
class MovieUpdateForm(forms.ModelForm):
class Meta:
model = Movie
fields = ['description']
reverse_lazy is important, so that when I click on my button it won't redirect me to consilium(my appname)/2/update and stays on the index site where I have my table
class MovieUpdateView(UpdateView):
model = Movie
form_class = MovieUpdateForm
success_url = reverse_lazy('consilium:index')
urls.py:
url(r'^(?P<pk>[0-9]+)/update/$', views.MovieUpdateView.as_view(), name='movie_update'),
here it was important to put this before my slug url pattern I had in my urls.py, otherwise it didn't work:
url(r'^(?P<slug>[\w_0-9]+)/$', views.MovieDetails.as_view(), name='detail'),
My form in my html: using pk=movie.pk so it will grab the correct movie and giving my textarea the name of "description" so my method knows where the data is coming from
<form action="{% url 'consilium:movie_update' pk=movie.pk %}" method="post" id="usrform">{% csrf_token %}
<textarea id="text" class ="form-control" name="description" readonly="true" onkeydown="expandtext(this)" ondblclick="this.readOnly='';">{{movie.description}}</textarea>
<input type="submit" id="set" class="pull-right"/>
</form>
So I have a table that lists all the record from my model.
But now I'm trying to make a Checkbox and delete it (kinda like the Django admin way), I can't find the documentation for this , as I'm sure there are several ways to to this.
But I'm trying to figure out like whats the proper way for doing this , should I do this via view ?
How to create single delete button for multiple delete instances in html and view.I am not using form
I refreed this side but not get correct solution
Django: writing a view to delete an item with checkboxes
Deleting multiple rows in Django frontend
list.html
{% for obj in object_list %}
<tbody>
<tr>
<td><input type="checkbox" name="data" value="{{obj.id}}" ></td>
<td><a href='#' data-toggle="collapse" value="{{obj.id}}">{{ obj.id }}</td>
<td>{{ obj.Full_Name }}</td>
<td>{{ obj.Agency_Name}}</td>
<td>{{ obj.Date_of_Birth}}</td>
<td>{{ obj.Agency_Code}}</td>
<td><span class="label label-primary">{{ obj.Agent_Status}}</span></td>
<td class="text-right">
<i class="fa fa-list-alt" aria-hidden="true"></i>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
#<i class="fa fa-trash" aria-hidden="true"></i>
#Remove this button and create single button for multiple delete
</td>
</tr>
</tbody>
{% endfor %}
view.py
def Agent_List(request, id=None): #list items
queryset = Agent.objects.order_by('id')
#queryset = Agent.objects.all()
query = request.GET.get('q')
if query:
queryset=queryset.filter(
Q(Aadhaar_Number__icontains=query) |
Q(PAN_Number__icontains=query) |
Q(Account_Number__icontains=query)
).distinct()
context = {
"object_list": queryset,
"Full_Name ": "Agent_List",
}
return render(request, "customer/Agent_List.html", context)
def Agent_Delete(request, id=None):
instance = get_object_or_404(Agent, id=id)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("customer:Agent_List")
In def Agent_Delete(request, id=None) it delete single id.but How to delete selected multiple id.Thank you in advance.