I have 2 classes of users who can view a screen that lists all users in my app. The type of user is controlled by a Boolean field on the User model. The screen currently lists out the Users and various details about them (see below). Project Managers should see a read only view of the page where as Administrators should have the ability to edit the Users as well.
HTML for the screen.
<div class="card-body">
<div class="table-responsive">
<table class="table text-sm mb-0">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>First Name</th>
<th>Last Name</th>
<th>Is Contributor?</th>
<th>Is Project Manager?</th>
<th>Is is_administrator?</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<th scope="row">{{ user.id }}</th>
<td>{{ user.username }}</td>
<td><a class="btn btn-primary" href=" " role="button">{{ user.first_name }}</a></td>
<td>{{ user.last_name }}</td>
<td>{{ user.is_contributor }}</td>
<td>{{ user.is_projectmanager }}</td>
<td>{{ user.is_administrator }}</td>
<td><a class="btn btn-info" href="" role="button">Edit</a></td>
<td><a class="btn btn-danger" href="" role="button">Delete</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
I want to create a version of the screen available to admin users which allows them to view and update users all at once.
How can I create a form that updates all the users at once? I'm looking to build something that lists out the users with a list of the fields associated with the model and then gives the admin the ability to change those fields for multiple users at the same time, and then hit a save button to submit the form?
I was able to figure it out using Model form sets.
https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#model-formsets
I just created the form set as seen below.
UserFormSet = modelformset_factory(User,fields=('username','first_name','last_name','email','is_contributor','is_projectmanager','is_administrator'))
formset = UserFormSet()
context = {
# 'users':users,
'formset':formset,
}
return render(request, 'bugtracker_app/users.html', context)
Then I looped through it in the template:
</div>
{% for form in formset %}
{{form}}
{% endfor %}
</div>
It isn't formatted quiet the way I was picturing it yet (it renders the fields vertically as opposed to horizontally see below, but I'm sure I can find a way to fix that.
Related
I tried to print the client list and all the data is shown but I have no idea how to display<br> it in the table below. as I have added a client and it is stored in firestore but when I fetch the data from the collection the table is created and the client is fetched. !!! even when I print the client it is showing all the data but it still is not showing the details in the web. for better understanding I have attached image below.
in HTML I need to fetch the data from firestore database collection in this table. I added a link of a screenshot of the web for a better understanding.
allclients = db.collection("clients").get()
return render_template("admin/clients.html", client_lists=allclients )
{% block content %}
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Client Code</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Address</th>
<th scope="col">Contact</th>
<th scope="col">Status</th>
<th scope="col">Update</th>
<th scope="col">Action</th>
</tr>
</thead>
{% if client_lists %}
{% for client_list in client_lists %}
<tbody>
<tr>
<td>{{client_list.client_id}}</th>
<td>{{client_list.first_name}}</td>
<td>{{client_list.email}}</td>
<td>{{client_list.phone_number}}</td>
<td>{{client_list.address}}</td>
<td><button type="button" class="btn btn-success">Active</button></td>
<td><button type="button" class="btn btn-primary">Edit</button></td>
<td><button type="submit" class="btn btn-danger">Delete</button></td>
{% endfor %}
</tr>
</tbody>
</table>
{% else %}
<p class="clientnotfound">No Clients Found?, Why don't you try adding a clients.</p>
{% endif %}
{% endblock %}
[Image is below for better understanding][1]
[1]: https://i.stack.imgur.com/vGqqM.png
You may want to change your <tbody> to:
<tbody>
{% for client_list in client_lists %}
<tr>
<td>{{client_list.to_dict()["client_id"]}}</td>
<td>{{client_list.to_dict()["first_name"]}}</td>
<td>{{client_list.to_dict()["email"]}}</td>
<td>{{client_list.to_dict()["phone_number"]}}</td>
<td>{{client_list.to_dict()["address"]}}</td>
<td><button type="button" class="btn btn-success">Active</button></td>
<td><button type="button" class="btn btn-primary">Edit</button></td>
<td><button type="submit" class="btn btn-danger">Delete</button></td>
</tr>
{% endfor %}
</tbody>
You need to convert your client_lists to dictionary before using it.
You can also use client_list.get("email") but it can give you some problems.
What I have is this in my HTML code:
<table id="example" class="table table-striped">
<thead>
<tr>
<th scope="col">Index</th>
<th scope="col">Col2</th>
<th scope="col">Col3</th>
<th scope="col">Col4</th>
</tr>
</thead>
<tbody>
{% for item in rows %}
<tr>
<td><button formtarget="_blank"
name="input" type="submit"
formaction="/get"
value={{item[0]}}>{{item[0]}}</button></td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
</tr>
{% endfor %}
Notice that I am adding button as type 'submit' to send item[0] which is essentially the row id of a sqlite3 table back to Flask server view function '/get'. My Flask '/get' function is as follows:
#app.route('/get', methods =['GET', 'POST'])
def getfmhtml():
input = str()
if request.method == 'POST':
input = int(request.form['graph'])
return render_template('index.html', input = input)
When I click the button in a row in Index column however, no value item[0] is posted to the server (i.e. nothing happens, no error either). I want to know what's the problem in my code. I want to Post the row id from index column back to my Flask server.
posting below as per suggestion from Gnudiff that worked. Enclosing button in form tag post the value back to the server:
{% for item in rows %}
<tr>
<td><form action="/get" method="POST"><button formtarget="_blank"
name="input" type="submit"
formaction="/get"
value={{item[0]}}>{{item[0]}}</button>
</form>
</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
</tr>
{% endfor %}
I have three models in models.py which are Topic,Webpage and AccessRecord. class AccessRecord has foreign key relation with class Webpage i wanna use AccessRecord fields nut,date in html template which is used to display class Webpage content how we can access AccessRecord fields in which has a foreign relation with class Webpage ?
this is my model:
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage)
date = models.DateField()
nut = models.CharField(max_length=56)
def __str__(self):
return str(self.date)
this is my view:
def index(request):
webpage_list = Webpage.objects.all()
web_dict = {"web_records":webpage_list}
return render(request,'first_app/index.html',web_dict)
this is my template:
<body>
<h1>Hi, welcome to Django Level Two!</h1>
<h2>Here are your access records:</h2>
<div class="djangtwo">
{% if web_records %}
<table style="float: left">
<thead>
<th>Topic Name</th>
<th>Site name</th>
<th>Url Accessed</th>
<th>Date Accessed</th>
<th>Webpage nut</th>
</thead>
{% for web in web_records %}
<tr>
<td>{{ web.topic }}</td>
<td>{{ web.name }}</td>
<td>{{ web.url }}</td>
<td>{{ web.nut }}</td>
<td>{{ web.date }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</div>
</body>
You can also make views.py like
#views.py
def index(request):
return render(request,'first_app/index.html')
AND modify template like:-
<body>
<h1>Hi, welcome to Django Level Two!</h1>
<h2>Here are your access records:</h2>
<div class="djangtwo">
{% if web_records %}
<table style="float: left">
<thead>
<th>Topic Name</th>
<th>Site name</th>
<th>Url Accessed</th>
<th>Date Accessed</th>
<th>Webpage nut</th>
</thead>
<tr>
<td>{{ user.web.topic }}</td> #HERE
<td>{{ user.web.name }}</td> #HERE
<td>{{ user.web.url }}</td> #HERE
<td>{{ user.web.nut }}</td> #HERE
<td>{{ user.web.date }}</td> #HERE
</tr>
{% endfor %}
</table>
{% endif %}
</div>
</body>
AND IF YOU WANT LOOP,SO YOU CAN EASILY USER LOOP.
You can also try this way:
rename the name field to web in AccessRecord model.
models.py
class AccessRecord(models.Model):
web = models.ForeignKey(Webpage)
date = models.DateField()
nut = models.CharField(max_length=56)
def __str__(self):
return str(self.date)
Get all objects of AccessRecord model instead of Webpage model.
views.py
from django.http import HttpResponse
from django.template import loader
def index(request):
access_records = AccessRecord.objects.all()
context = { "access_records": access_records }
t = loader.get_template('first_app/index.html')
return HttpResponse( t.render( context, request ) )
Loop the access records in your template.
index.html
<body>
<h1>Hi, welcome to Django Level Two!</h1>
<h2>Here are your access records:</h2>
<div class="djangtwo">
{% if access_records %}
<table style="float: left">
<thead>
<th>Topic Name</th>
<th>Site name</th>
<th>Url Accessed</th>
<th>Date Accessed</th>
<th>Webpage nut</th>
</thead>
{% for access_record in access_records %}
<tr>
<td>{{ access_record.web.topic }}</td>
<td>{{ access_record.web.name }}</td>
<td>{{ access_record.web.url }}</td>
<td>{{ access_record.nut }}</td>
<td>{{ access_record.date }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</div>
</body>
I have a Django form and want the user to be able to tab to the username, password and login button in that order.
tabindex does not seem to work in my template. Instead it moves to username, login button and password in that order.
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td><div tabindex="1">{{ form.username }}</div></td>
<td rowspan="2"><div tabindex="3"><button type="submit" class="btn btn-success">Login</button></div></td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td><div tabindex="2">{{ form.password }}</div></td>
</tr>
</table>
</form>
what am I doing wrong?
I think you have to define a custom template filter that adds a tabindex attribute to the widget of a bound field:
How to add filter in templates ?
Ans - You have to create one directory in your app named 'templatetags'. You'll want this directory to be recognized as a Python package, so make sure you create an empty __init__.py file. Next, go ahead and create the Python file that will hold your tags and name it something like app_filters.py or a similar name that is easily identifiable. It is look like...
Django Project
-> my_app
---> models.py
---> views.py
---> templatetags
-----> __init__.py
-----> app_filters.py
For more click here
app_filters.py
from django import template
register = template.Library()
#register.filter
def tabindex(value, index):
"""
Add a tabindex attribute to the widget for a bound field.
"""
value.field.widget.attrs['tabindex'] = index
return value
NOTE : After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.
Then, add |tabindex:n to the fields in the template. For example:
your_html_file.html
{% load app_filters %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td><div>{{ form.username|tabindex:1 }}</div></td>
<td rowspan="2"><div><button tabindex="3" type="submit" class="btn btn-success">Login</button></div></td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td><div>{{ form.password|tabindex:2 }}</div></td>
</tr>
</table>
</form>
I created a sqlite database containing a bunch of formatted html code. When I try to send it to a HTML table the code is coming in as HTML source code and not being formatted. Yet if I copy and paste the same code one at a time in table cells it formats. How to get code to format when it's coming in from flask/sqlite? I'm getting the table to load I just want the 'formatteddax' column to have the formatting applied. thanks
how the data looks now:
html file
<table>
<thead>
<tr>
<th>Measure</th>
<th>Formatted DAX</th>
</tr>
</thead>
<tbody>
{% for measure in measures %}
<tr>
<td>{{ measure[0] }}</td>
<td>{{ measure[2] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
app.py file
app = Flask(__name__)
engine = create_engine('sqlite:///C:\\Users\\xyz\\Documents\\DAX-formatter\\dax2.sqlite')
Base = automap_base()
Base.prepare(engine, reflect = True)
session = Session(engine)
#app.route("/", methods = ['GET'])
def daxionary():
cursor = engine.execute('SELECT Measure, formatteddax FROM daxionary2')
return render_template('daxionary.html', measures=cursor.fetchall())
you need to mark your HTML safe by using safe filter.
{% for measure in measures %}
<tr>
<td>{{ measure[0] | safe }}</td>
<td>{{ measure[2] | safe }}</td>
</tr>
{% endfor %}
Further read Controlling Autoescaping