Cannot able to display data from database in Django 1.10? - html

I am new to django and i cannot able to display data from postgres database, i have following data in my database,
Data in products Table
1 "test" "images.jpg" 1
3 "sample" "images.jpg" 2
and my code is ,
views.py
from django.shortcuts import render
from products.forms import productsform
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from products.models import products
def productsview(request):
if request.method == 'POST':
form = productsform(request.POST)
if form.is_valid:
name = request.POST.get('name')
image = request.POST.get('image')
code = request.POST.get('code')
products_obj = products(name=name,image=image,code=code)
products_obj.save()
return HttpResponse("Register Successfull")
else:
form = productsform()
return render(request,'products/products_view.html',{'form':form,})
def display(request):
query_results = products.objects.all()
return render(request, 'products/myview.html')
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.productsview, name='products'),
url(r'^display', views.display, name='display'),
]
models.py
from __future__ import unicode_literals
from django.db import models
class products(models.Model):
name = models.CharField(max_length=15,unique=True)
image = models.ImageField(upload_to = 'pictures')
code = models.IntegerField()
myview.html
<table>
<tr>
<th>Name</th>
<th>Code</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.name }}</td>
<td>{{ item.code }}</td>
</tr>
{% endfor %}
</table>

You're not sending the data to the view from the display function.
return render(request, 'products/myview.html', {'query_results': query_results})

You forgot passing the model to the template. In you views.py file, do the following:
def display(request):
query_results = products.objects.all()
return render(request, 'products/myview.html', {'query_results': query_results})

Related

Django database data not showing in Templete

I have a class HardBook that inherits from Book:
class Book(models.Model):
title = models.CharField('Book Title', max_length=200)
image = models.ImageField('Book Cover', upload_to='covers')
description = models.CharField('Description', max_length= 350)
class HardBook(Book):
quantity = models.IntegerField('Quantity')
views.py
class BookCreateView(CreateView):
def get_context_data(self,**kwargs):
context = super(BookCreateView, self).get_context_data(**kwargs)
context['softbooks'] = SoftBook.objects.all()
context['hardbooks'] = SoftBook.objects.all()
return context
I want to display the field data in a table, I want to show title, image and quantity. Everthing is displayed except quantity.
{% for hardbook in hardbooks %}
<tr>
<td>
<div class="cover-image" style="background-image:url({{hardbook.image.url}});"></div>
</td>
<td>{{hardbook.title}}</td>
<td>{{hardbook.quantity}}</td>
</tr>
{% endfor %}

Django: How to display some objects to specific users only

I am new to django and working on a project where admin have to assign a team to manager and when ever admin assign a team to manager then it will be shown on that manager's dashboard only.I have no idea how can i do this. Please if someone can help please help me.
here is my .html file for admin from where admin can assign team to manager.
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>Assign TEAM</th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<form id="form_id" method="POST" action = "{% url 'accept' %}">
{% csrf_token %}
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>
<select name="manager_{{manager.id}}">
{% for manager in managers %}
<option value ="{{manager.id}}">{{manager.name}}</option>
{% endfor %}
</select>
</td>
<td>
<input class="btn btn-raised btn-primary btn-round waves-effect" type="submit" value="Assign">
</td>
</tr>
{% endfor %}
here is my model for the team and manager:
class Create_Team(models.Model):
first_name = models.CharField(max_length= 50)
last_name = models.CharField(max_length= 50)
company_name = models.CharField(max_length= 100)
address = models.CharField(max_length= 1000)
state = models.CharField(max_length= 100)
city = models.CharField(max_length= 100)
status = models.CharField(max_length= 30)
managers = models.ForeignKey('manager', on_delete = models.SET_NULL, null=True)
class manager(models.Model):
name = models.CharField(max_length= 500)
designation = models.CharField(max_length= 500)
here is my views.py file for manager and from where the admin is accepting the request:
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
managers = manager.objects.all()
if request.method == 'POST':
createteam = Create_Team()
createteam_id = int(request.POST.get('team', 1))
manager_id = int(request.POST.get('manager', 1))
createteam = Create_Team.objects.get(pk=createteam_id)
createteam.manager = manager.objects.get(pk=manager_id)
createteam.save()
return render(request, "admin/accept.html", {"object": obj, "managers": managers})
def superior(request):
return render(request, 'manager/index-3.html')
here is my views where i am checking whether the user is admin or user or manager
def login(request):
if request.method =='POST':
# print(request.POST)
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
print (user.has_perm('app.edit_task'))
# return redirect('index')
if user.is_superuser:
return redirect('master')
# elif user.has_perm('app.edit_task'):
# return redirect('manager')
elif user.is_staff:
return redirect('manager')
else:
return redirect('index')
else:
messages.error(request, 'Invalid Credentials')
return redirect('login')
else:
return render(request, 'vadash/sign-in.html')
I want that whenever the admin will click on the assign button then that team will be displayed to that manager.Please help me. But this code isn't updating the database.
After Manager Logins, Make sure that you retrieve the data of the manager that is logged in. and pass that data to the view
Make custom user Model to check if logged in user is manager,admin or member.
You can make custom user by different methods.Please check the link:
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
You might give boolean fields like is_manager , is_member etc
After defining custom user model you can check if logged in user is manager ,admin etc using
request.user.is_manager == True

Is there a way to delete a row from an HTML table with user input using Flask (jinja2)?

I'm new to Flask and programming. I'm creating a simple database using Flask/SQLite. I'm having users enter the data in a form and having that data populate on an HTML table next to the form. I've managed to achieve this. However, I've like to add the ability of a user to delete a row in the table.
I've created a function in my routes.py that I've like to utilize, but I can't find a way to pass user submitted information back to my routes.py function. I've tried using an HTML link but I don't want to pass the user to another URL and back. Is there a way to achieve this?
From routes.py
#app.route("/")
#app.route('/interventions', methods=['GET', 'POST'])
#login_required
def interventions():
.....
qinter = Interventions.query.all()
def delete_entry(entry):
db.session.delete(qinter[(entry-1)])
db.session.commit()
return redirect(url_for('interventions'))
.....
From Interventions.html
.........
<table border="1">
<tr>
<th>Delete?</th>
<th>Date</th>
<th>Chart #</th>
<th>Provider</th>
<th>Pharmacist</th>
<th>COI</th>
<th>Accepted?</th>
<th>Intervention</th>
</tr
{% for q in qinter %}
<tr>
<td><delete</td>
<td>{{ q.date }}</td>
<td>{{ q.chart }}</td>
<td>{{ q.prescriber }}</td>
<td>{{ q.pharmacist }}</td>
<td>{{ q.category }}</td>
<td>{{ q.accepted }}</td>
<td>{{ q.intervention }}</td>
</tr>
{% endfor %}
</table>
What you need is some way to communicate from your HTML template to your interventions route that you want to delete a certain row in your database table. To do that you need to add some additional parameters to your route function, like this:
#app.route('/interventions', methods=['GET', 'POST'])
#app.route('/interventions/<action>/<item_id>', methods=['GET', 'POST'])
#login_required
def interventions(action=None, item_id=None):
def delete_entry(entry):
db.session.delete(entry)
db.session.commit()
if request.method == "POST":
if action == 'delete':
# Get specific row user wants to delete
qinter_row_to_delete = Interventions.query.get(item_id)
# Delete row
delete_entry(qinter_row_to_delete)
return redirect(url_for('interventions'))
elif request.method == "GET":
qinter = Interventions.query.all()
# Render template etc...
Then from Jinja template make a call to that endpoint to delete the row:
<form id="form" action="{{url_for('interventions', action='delete', item_id=q.id)}}" method="POST">

Django: can "double" 'render_to_response' be unified into only one view?

I have defined two functions in views.py to obtain first prova.html with certain elementimenu and then, after clicking over one of them, I obtain again the page with elementimenu and elementi associated to elementimenu with the same id i.e.:
another_app.model.py
...
class ElementiTab(models.Model):
author = models.ForeignKey('auth.User', null=True, blank=False)
des = models.CharField(max_length=30)
x = models.FloatField()
y = models.FloatField()
res = models.FloatField(default=0)
created_date = models.DateTimeField(default=timezone.now)
...
And here the code that I like to get better:
views.py
from another_app.model import ElementiTab
def show_elementi(request):
elementimenu = ElementiTab.objects.all()
return render_to_response('homepage/prova.html',{'elementimenu': elementimenu, 'user.username': request}, context_instance = RequestContext(request))
def show_detail(request,id):
elementimenu = ElementiTab.objects.all()
detail = get_object_or_404(ElementiTab, pk=id)
return render_to_response('homepage/prova.html',{'elementimenu': elementimenu, 'detail': detail, 'user.username': request}, context_instance = RequestContext(request))
urls.py
...
url(r'^homepage/prova/$', views.show_elementi),
url(r'^show_detail/(?P<id>\d+)/$', views.show_detail),
...
prova.html
...
<div class="elementi">
{% for elementi in elementimenu %}
{{elementi.des}}
{% endfor %}
</div>
<div class="table-responsive">
<table class="table table-bordered">
<tr class="info">
<td width="35%" align="center"> NOME</td>
<td width="35%" align="center"> DATA CREAZIONE </td>
<td width="30%" align="center"> AUTORE </td>
</tr>
{% if detail %}
<div class="dettagli">
<tr>
<td>{{detail.des}}</td>
<td>{{detail.created_date}}</td>
<td>{{detail.author}}</td>
</tr>
{% endif %}
</div>
</table>
</div>
...
I had used this "trick" in show_detail view so that I can see elementimenu even after calling this function.
Is there a more elegant way to do this?
Yes, you can use the single view. Add the default None value for the id (or pk) argument:
def show_elementi(request, pk=None):
elementimenu = ElementiTab.objects.all()
detail = get_object_or_404(ElementiTab, pk=pk) if pk else None
return render(request, 'homepage/prova.html',
{'elementimenu': elementimenu, 'detail': detail})
And then map both urls to this view:
url(r'^homepage/prova/$', views.show_elementi),
url(r'^show_detail/(?P<pk>\d+)/$', views.show_elementi),

How can I take input from a text field in a Django page then update a SQL table with the response?

I am working on a site that will be used to clean up inactive Tableau workbooks. Logging into this site will allow my users to see their old workbooks and decide which ones to keep.
This is going to be accomplished by taking some simple text input from an HTML page, K for keep | D for delete.
The response from the user will then be stored as a Python variable that will go into an if then statement. The if then statement will basically update each row in SQL, adding either K or D to a column called "Marked_for_Deletion".
From there, a stored procedure will run, check that column, and delete all things marked with a D.
Is this feasible? If so, how would I go about pulling that input and making sure it gets added to the right column/row? If not, can you offer any suggestions on a substitute method I can use?
Thanks!
Edit: Here is the code for my table.
<table class="blueTable">
<thead>
<tr>
<th>Workbook Name</th>
<th>Deletion Deadline</th>
<th>Keep or Delete?</th>
</tr>
</thead>
<tbody>
{% for book in Workbooks %}
<tr>
<td>{{ book.name }}</td>
<td>{{ book.owner_name }}</td>
<td>
<label class="container" style="margin-bottom: 25px">
<input type="text" placeholder="(Enter K for Keep, D for Delete)">
</label>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<form method="post">
{% csrf_token %}
<button type="submit" name="run_script">Submit</button>
</form>
</body>
</html>
I want to be able to pull the input from the last td tag and store it with the submit button below there.
I'm kind of late, but I hope it helps you out.
urls.py
from django.urls import path
from workbook_app import views
app_name = 'workbook_app'
urlpatterns = [
path('books/', views.BookListView.as_view(), name='books'),
path('keep_or_delete/<int:pk>/', views.KeepOrDeleteView.as_view(), name='keep_or_delete'),
]
models.py
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=250)
owner_name = models.CharField(max_length=250)
marked_for_deletion = models.BooleanField(default=False)
views.py
from django.views.generic import ListView
from workbook_app.models import Book
from django.http import HttpResponse, HttpResponseRedirect
from django.views import View
from django.urls import reverse
class BookListView(ListView):
template_name = 'workbook_app/books.html'
def get_queryset(self):
return Book.objects.all()
class KeepOrDeleteView(View):
def post(self, request, pk):
book = Book.objects.get(pk=pk)
print(book, book.marked_for_deletion, not book.marked_for_deletion)
book.marked_for_deletion = not book.marked_for_deletion
book.save()
url = reverse('workbook_app:books')
return HttpResponseRedirect(url)
books.html
<div class="container">
<h2>Books</h2>
<table class="table">
<tr>
<th>Workbook Name</th>
<th>Deletion Deadline</th>
<th>Keep or Delete?</th>
</tr>
{% for book in object_list %}
<tr>
<td>{{book.name}}</td>
<td>{{book.owner_name}}</td>
<td>
<form action="{% url 'workbook_app:keep_or_delete' pk=book.pk %}" method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-{%if book.marked_for_deletion %}primary{% else%}danger{% endif %}">{%if book.marked_for_deletion %}Keep{% else%}Delete{% endif %}</button>
</form>
</td>
</tr>
{%endfor%}
</table>
P.S. I'm not handling exceptions, messages, etc. You're just gonna have to figure it out yourself or open a new question.