This is my List in the HTML document
I have a Django post view, when I hit send I want the selected users to be posted to the students field.
As you can see I have tried to do the instance and user thing from this url but I can't figure it out!
HTML:
{% for elev in elever %}
<div class="custom-control custom-checkbox">
<span class="d-flex align-items-center">
<div style="margin-right: 10px">
<div class="circle" style="background-color: {{ elev.color }}">
<span class="initials" , style="color: #ffffff"> {{ elev.user|capfirst|first }}
</span>
</div>
</div>
<div style="width: 300px">
<span class="h6 mb-0" data-filter-by="text">{{elev.user|capfirst}}</span>
</div>
<div class="checkboxx"> <input type="checkbox" name="Studyplan-Canview" value= "{{ student.name }}">
<style>
.checkerName {
margin-left: 10px
}
.checkboxx {
align-content: flex-end;
margin-left: 300px
}
</style> </div>
</span>
</label>
</div>
{% endfor %}
The View:
#post request checker
#login_required
def skapa_studieplan(request):
if request.method == 'POST':
name = request.POST.get('Studyplan-Name')
description = request.POST.get('Studyplan-Description')
parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID'))
users = UserProfile.objects.all()
instance = Studyplan.objects.create(request.POST.get('Studyplan-Canview'))
for user in users:
instance.canview.add(user)
studyplan = Studyplan(name=name, description=description, parent_assignment=parent_assignment, canview=instance)
studyplan.save()
return redirect('allaStudieplaner')
Related
I have an issue with my update button and it show this error to me when I click the update button, it is suppose to redirect me to the next page where the staff can update the details, how do I fix that error, so that it can redirect me to the next page where it will show the forms for the staff to update the details
The error I had is shown below here (Traceback error):
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/updatedata/21/
Django Version: 3.1.4
Python Version: 3.8.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account.apps.AccountConfig',
'crispy_forms',
'channels']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response
self.check_response(response, callback)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 307, in check_response
raise ValueError(
Exception Type: ValueError at /updatedata/21/
Exception Value: The view account.views.updatedata didn't return an HttpResponse object. It returned None instead.
views.py
#login_required()
def updatedata(request, id):
photo = get_object_or_404(Photo, id=id)
if request.method == 'POST': # check for the post request body
form = UpdateForm(request.POST)
if form.is_valid():
form.save()
return redirect('/logdata')
else:
msg = 'form is not valid' # Show an error message if the form is not valid
else:
form = UpdateForm()
context = {
"form": form,
"photo": photo
}
return render(request, 'updatedata.html', context)
logdata.html
{% extends "home.html" %}
{% block content %}
<style>
table {
border-collapse:separate;
border:solid black 1px;
border-radius:6px;
-moz-border-radius:6px;
}
td, th {
border-left:solid black 1px;
border-top:solid black 1px;
}
th {
border-top: none;
}
td:first-child, th:first-child {
border-left: none;
width: 180px;
}
.pagination a {
padding: 10px;
}
.sort {
display: inline;
margin: 0 20px 0 20px;
}
ul.pagination li a {
display: block;
padding: 5px 15px;
}
ul.pagination li.active {
padding: 5px 15px;
background-color: hsla(199, 34%, 55%, 1);
border-radius: 30px;
color: white;
}
ul.pagination li.disabled {
padding: 5px 15px;
}
ul.pagination li {
display: block;
//border: 1px solid hsla(199, 34%, 64%, 0.74);
}
ul.pagination li a:hover,
ul.pagination li a:active {
border-radius: 30px;
background-color: hsla(199, 34%, 64%, 0.74);
}
#media only screen and (min-width: 268px) {
ul.pagination {
display: flex;
justify-content: left;
align-items: right;
font-size: 18px;
}
</style>
<script>
// Function to download table data into csv file
function download_table_as_csv(table_id, separator = ',') {
var rows = document.querySelectorAll('table#' + table_id + ' tr');
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
data = data.replace(/"/g, '""');
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
</script>
<div style="padding-left:16px">
<br>
<div class="form-block">
<h6>Search for Part Number/ Serial Number/ Reception Number/ MCO Number/ Customer Name/ Current Status</h6>
<form class="form-inline my-2 my-lg-0" action="{% url 'logdata' %}" method='GET' value='{{ request.GET.q }}'>
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'/>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
<div class="sort">
<h5 class="col-md-3">Sort By : </h5>
<div id="sortBlock" class="col-md-9">
<form class="form-inline my-2 my-lg-0" action="" method='GET' value='{{ request.GET.sortType }}'>
<div class="sort">
<input type="radio" id="partno" name="sortType" value="partno">
<label for="partno">Part Number</label>
</div>
<div class="sort">
<input type="radio" id="serialno" name="sortType" value="serialno">
<label for="serialno">Serial Number</label>
</div>
<div class="sort">
<input type="radio" id="mcoNum" name="sortType" value="mcoNum">
<label for="mcoNum">MCO Number</label>
</div>
<div class="sort">
<input type="radio" id="Customername" name="sortType" value="Customername">
<label for="Customername">Customer Name</label>
</div>
<div class="sort">
<input type="Submit" value="Sort"/>
</div>
</form>
</div>
</div>
<br>
<table id="viewTable" class="m-2">
<i class="fa fa-download" aria-hidden="true"></i>
Download as CSV
<br>
<tr class="header">
<th>Latest Log</th>
<th>Part Number</th>
<th>Serial Number</th>
<th>Reception Number</th>
<th>MCO Number</th>
<th>Customer Name</th>
<th>Current Status</th>
<th>Next Status</th>
<th>Action</th>
</tr>
{% for photo in allusername %}
<tr>
<td>{{photo.Datetime}}</td>
<td>{{photo.partno}}</td>
<td>{{photo.serialno}}</td>
<td>{{photo.reception}}</td>
<td>{{photo.mcoNum}}</td>
<td>{{photo.Customername}}</td>
<td>{{photo.status}}</td>
<td>{{photo.nextstatus}}</td>
<td>
<form action="{% url 'logdetails' photo.id %}" method="post">
{% csrf_token %}
<button type="submit" class="btn btn-sm btn-info">View</button>
</form>
</td>
<td>
<form action="{% url 'updatedata' photo.id %}" method="post">
{% csrf_token %}
<button type="submit" name="update_staff_page" class="btn btn-sm btn-info">Update</button>
</form>
{% endfor %}
</table>
<br>
{% if allusername.has_other_pages %}
<ul class="pagination pr-3 mr-1 ml-auto">
{% if allusername.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in allusername.paginator.page_range %}
{% if allusername.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if allusername.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
{% endblock %}
forms.py
class UpdateForm(forms.ModelForm):
mcoNum = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
reception = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
partno = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
serialno = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
Customername = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
class Meta:
model = Photo
fields = ("mcoNum", "reception", "partno", "serialno")
def __init__(self, *args, **kwargs):
super(UpdateForm, self).__init__(*args, **kwargs)
self.fields['mcoNum'].required = False
self.fields['reception'].required = False
self.fields['partno'].required = False
self.fields['serialno'].required = False
updatedata.html
<!doctype html>
{% extends "home.html" %}
{% block content %}
{% load static %}
<html lang="en">
<head>
<style>
.button {
background-color: #38d39f;
border-color: #38d39f;
color: white;
padding: 10px 20px;
text-align: center;
display: inline-block;
margin: 4px 2px;
cursor: pointer;
border-radius: 16px;
width: 275px;
}
</style>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}">
<link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<!-- Style -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">
<button type = "button" class="close" data-dismiss = "alert">x</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
<div style="padding-left:16px">
<table class="first" cellspacing="0" cellpadding="0">
<tr>
<h5>Current Log Data</h5>
</tr>
<br>
<tr>
<th>MCO Number: {{photo.mcoNum}}</th>
</tr>
<tr>
<th>Reception Number: {{photo.reception}}</th>
</tr>
<tr>
<th>Part Number: {{photo.partno}}</th>
</tr>
<tr>
<th>Serial Number: {{photo.serialno}}</th>
</tr>
<tr>
<th>Customer Name: {{photo.Customername}}</th>
</tr>
</table>
<div class="content">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6 contents">
<div class="row justify-content-center">
<div class="col-md-25">
Go Back
<div class="form-block">
<div class="mb-3">
</div>
<h2>Update Log Data</h2>
<br/>
<form method="post">
{% csrf_token %}
<br>
<div class="form-group first">
<label for="MCO">MCO Number</label>
{{ form.mcoNum }}
</div>
<br>
<div class="form-group last mb-4">
<label for="Reception">Reception Number</label>
{{ form.reception }}
</div>
<br>
<div class="form-group last mb-4">
<label for="partno">Part Number</label>
{{ form.partno }}
</div>
<br>
<div class="form-group last mb-4">
<label for="serialno">Serial Number</label>
{{ form.serialno }}
</div>
<br>
<div class="form-group last mb-4">
<label for="Customername">Customer Name</label>
{{ form.Customername }}
</div>
<button class="button" >Submit</button>
<br>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'js/popper.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/main.js' %}"></script>
</div>
{% endblock %}
change your view into this
views.py
from django.http import Http404
from django.contrib import messages
#login_required()
def updatedata(request, id):
try:
photo = Photo.objects.get(id=id)
if request.method == 'POST' and 'update_staff' not in request.POST: # check for the post request body
form = UpdateForm(request.POST)
if form.is_valid():
form.save()
return redirect('/logdata')
else:
messages.add_message(request, messages.ERROR, 'form is not valid') # Show an error message if the form is not valid
else:
form = UpdateForm(instance=photo)
context = {
"form": form,
"photo": photo
}
return render(request, 'updatedata.html', context)
except Exception as e:
raise Http404
and your template into this
logdata.html
<form action="{% url 'updatedata' photo.id %}" method="post">
{% csrf_token %}
<button type="submit" name="update_staff_page" class="btn btn-sm btn-info">Update</button>
</form>
i think you not make clear statement, if the post don't send any data on method post you submit
I have following products in the database:
Html code for the above image:
{% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %}
<tbody>
<tr>
<td data-th="Product">
<div class="row">
<div class="col-sm-2 hidden-xs"><img alt="..." class="img-responsive" src="http://placehold.it/100x100"/>
</div>
<div class="col-sm-10">
<h4 class="nomargin">{{crops_ordered_names}}</h4>
<p>Available amount: {{crops_ava}}</p>
</div>
</div>
</td>
<td data-th="Price" data-type="price">{{crops_ordered_cost}}</td>
<td data-th="Quantity">
<input class="form-control text-center" data-type="quan" max="{{crops_ava}}" min="1" type="number">
</td>
<td class="text-center" data-th="Subtotal" data-type="subtotal"></td>
<td class="actions" data-th="">
<a href="{% url 'shopping_cart:delete_item' crops_ordered_names%}">
<button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
</a>
</td>
</tr>
</tbody>
How can I send the value quantity of each item to the django views to store quantity of each item to the respective product when I submit the form after entering all the quantities.
I need to get value of quantity from the HTML code:
<input type="number" class="form-control text-center" data-type="quan" min="1" max="{{crops_ava}}" >
I was working on something similar. And I've used ajax to update the quantity. I'm not very good at explaining things, but I tried.
Get the quantity of the unique item using id="quantity{{item.id}}
<div style="flex:1">
<p id="quantity{{ item.id }}" class="align-content-center quantity">{{ item.quantity }}</p>
<div class="quantity_btns">
<img height="15" width="15" class="chg-quantity update_cart" data-product="{{ item.id }}" data-action="add" src="{% static 'images/arrow-up.png' %}">
<img height="15" width="15" class="chg-quantity update_cart" data-product="{{ item.id }}" data-action="remove" src="{% static 'images/arrow-down.png' %}">
</div>
</div>
And below is the ajax code.
let update_cart = document.getElementsByClassName('update_cart');
for (var i = 0; i < update_cart.length; i++) {
update_cart[i].addEventListener('click', function() {
var data_action = $(this).data('action');
var product_id = $(this).data('product');
let quantity = document.getElementById('quantity' + product_id);
$.ajax({
url:'/test_add_cart_button',
data:{
'data_action':data_action,
'product_id':product_id,
},
success: function(data){
quantity.innerHTML = data.item_quantity;
}
});
});
}
Little summary of above code. We get all the elements with class "update_cart". Loop through all the elements. Get the attribute value of data-action which contains add/remove action. Then get the attribute data-product(which contains the {{ item.id }}). Get the quantity of the product the using getElementById('quantity' + product_id). Where the product_id will be retrieved from the data-product.
Then in the ajax, we send the value we captured in a key to send it to our view.
def test_add_cart_button(request):
clicked = request.GET.get('data_action')
product_id = request.GET.get('product_id')
item = CartItem.objects.get(id=product_id, user=request.user)
if clicked == 'add':
item.quantity += 1
item.save()
elif clicked == 'remove':
item.quantity -= 1
if item.quantity <= 0:
remove_from_cart(request, item.id)
return JsonResponse({'item_quantity':item.quantity,}, safe=False)
With data_action and product_id keys. We can use them in our view by request.GET.get('data_action') and request.GET.get('product').
its quite similar my projects. I think this code help you
models.py
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.item.product_title} No. of quantity : {self.quantity}"
def get_total_item_price(self):
return self.quantity * self.item.product_price
def get_total_discount_item_price(self):
return self.quantity * self.item.product_discount_price
def get_amount_saved(self):
return self.get_total_item_price() - self.get_total_discount_item_price()
def get_final_price(self):
if self.item.product_discount_price:
return self.get_total_discount_item_price()
return self.get_total_item_price()
views.py
class Cartview(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
context = {
'object': order
}
return render(self.request, 'cart.html', context)
except ObjectDoesNotExist:
messages.warning(self.request, "You do not have an active order")
return redirect("/")
Jinja template with for looping
<tbody>
{% for order_item in object.items.all %}
<tr class="text-center">
<td class="product-remove"><span style=color:burlywood; class="badge badge-light">{{forloop.counter}}</span></td>
<td class="image-prod">
<div class="img" style="background-image:url({{order_item.item.product_image.url}});"></div>
</td>
<td class="product-name">
<h3>{{order_item.item.product_title}}</h3>
<p>{{order_item.item.product_description}}</p>
</td>
<td class="price">
{% if order_item.item.product_offer %}
<span class="ml-2 price-sale">₹ {{order_item.item.product_discount_price}}</span> {% else %}
<span class="price-sale">₹ {{order_item.item.product_price}}</span> {% endif %}
</td>
<td class="quantity">
<div class="input-group mb-3">
-
<input type="text" name="quantity" class="quantity form-control input-number" value="{{ order_item.quantity }}">
+
</div>
</td>
<td class=" total ">
{% if order_item.item.product_offer %} ₹ {{ order_item.get_total_discount_item_price }}
<span class="badge badge-info">Saving ₹ {{ order_item.get_amount_saved }}</span> {% else %} ₹{{ order_item.get_total_item_price }} {% endif %}
</td>
<td class="product-remove"><span class="ion-ios-close"></span></td>
{% empty %}
<tr>
<td colspan='6'>Your cart is empty</td>
</tr>
</tr>
{% endfor %}
<!-- END TR-->
</tbody>
</table>
</div>
</div>
</div>
<div class="row justify-content-start ">
<div class="col col-lg-5 col-md-6 mt-5 cart-wrap ftco-animate ">
{% if object.get_total %}
<div class="cart-total mb-3 ">
<h3>Cart Totals</h3>
<p class="d-flex ">
<span>Subtotal</span>
<span>{{object.get_total}}</span>
</p>
<p class="d-flex ">
<span>Delivery</span>
<span>0.00</span>
</p>
<p class="d-flex ">
<span>Discount</span>
<span>0.00</span>
</p>
<hr>
<p class="d-flex total-price ">
<span>Total</span>
<span> ₹ {{object.get_total}}</span>
</p>
</div>
{% endif %}
follow this Django build-in functions documents
Hey I am quite new to django, I have this function for comments and replies,the problem is I can't have the reply to comments instead it is getting posted as comments. How to have this replies under respective comments? Here is my model and functions.
model
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
reply = models.ForeignKey('Comment', null=True, related_name='replies', blank=True, on_delete=models.CASCADE)
content = models.TextField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
views
def comment_section(request, slug):
user = request.user
post = get_object_or_404(Post, slug=slug)
comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
if request.POST:
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
content = request.POST.get('content')
reply_id = request.POST.get('comment_id') #reply-section
comment_qs = None
if reply_id:
comment_qs = Comment.objects.get(id=reply_id)
comment = Comment.objects.create(post=post, user=request.user, content=content, reply=comment_qs)
comment.save()
else:
comment_form = CommentForm()
context = {
'post':post,
'comment_form':comment_form,
'comments': comments,
}
if request.is_ajax():
html = render_to_string('posts/comment_section.html', context, request=request)
return JsonResponse({'form': html})
html
<!-- Comment showing section -->
<div class="main-comment-section">
<div class="container-fluid mt-2">
<div class="form-group row">
<!-- Comment Form -->
<form class="comment-form" method="post" action="{% url 'posts:comment_section' post.slug %}">
{% csrf_token %}
<div class="form-group">
<textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea>
</div>
<button type="submit" value="submit" class="btn-sm btn-outline-warning" style="color: black;">Comment</button>
</form>
<!-- Comment Form end -->
</div>
</div>
{% if not post.comment_set.all %}
<small>No comments to display</small>
{% endif %}
{% for comment in post.comment_set.all %}
<blockquote class="blockquote">
<img style="float:left; clear: left;" class="rounded-circle article-img" height="10" width="10" src="{{ comment.user.profile.profile_pic.url }}"><h6>{{ comment.user.first_name|capfirst }} {{ comment.user.last_name|capfirst }}</h6><br>
<p style="font-size: 8px;">{{ comment.timestamp }}</p>
<p style="font-size: 14px;" class="mb-3">{{ comment.content }}</p>
<a type="button" name="button" class="reply-btn ml-4"><i class="fas fa-reply fa-sm"></i></a>
{% if request.user == comment.user %}
<i class="fas fa-trash fa-sm" style="color: brown;"></i></td>
{% endif %}
</blockquote>
{{ comment.reply.count }}
<div class="replied-comments col-md-5" style="display: none;">
{% for reply in comment.replies.all %}
<blockquote class="blockquote">
<img style="float:left; clear: left;" class="rounded-circle article-img" height="50" width="50" src="{{ reply.user.profile.profile_pic.url }}"><h6>{{ reply.user.first_name|capfirst }} {{ reply.user.last_name|capfirst }}</h6><br>
<p style="font-size: 13px;" class="mb-3">{{ reply.content }}</p>
</blockquote>
{% endfor %}
<div class="form-group row">
<form class="reply-form" method="post" action="{% url 'posts:comment_section' post.slug %}">{% csrf_token %}
<input type="hidden" name="comment_id" value="{{ comment.id }}">
<div class="form-group">
<textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea>
</div>
<input type="submit" value="submit" class="btn-sm btn-outline-light" style="color: black;">
</form>
</div>
</div>
{% endfor %}
</div>
I guess there is some problem with the form submission, but I can't figure out what it is.
Thanks
This is how I easily solve the problem and it helps me in many ways.
comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
{% for comment in comments %}
{% if comment.reply %}
The IF statement will check if the comment is a reply, this have a parent
If it is, you can access it with {{comment.reply.content}} and {{comment.reply.timestamp}} to print the parent. And {{comment.content}} to print the reply.
{% else %}
I.e. if the comment is just a comment and not a reply.
Just print the comment
{{comment.content}}
{% endfor %}
It is because replies are also comments. You are loading comments in views correctly by :
comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
but in the template you are loading both comments and replies in :
{% for comment in post.comment_set.all %}
try :
{% for comment in comments %}
to load post comments and select replies of each comment by :
{% for reply in comment.replies.all %}
I have a created a form using HTML and Jinja2 to configure a CSV file. The user is asked to change the name and assign a type to each column name. The CSV file can have any number of columns, therefore, I have created the form through looping Currently, I use the bootstrap grid and divide into three columns and rows depending on the number of columns.
<form action="/updateFile" method="POST" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-12">
<p class="form-group">
{% for x in title %}
{% if loop.index == 1 %} <div class="row"> {% endif %}
<div class="col-xs-12 col-sm-12 col-lg-4 col-md-4">
<div class="row">
<div class="col-sm-6">
<label> Field {{ loop.index }} : {{ x }} </label>
<input type="text" title="Name should only contain letters or numbers" class="form-control"
name="field-{{ loop.index }}" value="{{ x }}" maxlength="10" pattern="[a-zA-Z0-9_ ]+" required>
</div>
<div class="col-sm-6 pull-right">
<label> </label>
<select class="form-control " name="choice-{{ loop.index }}">
<option value="mcqsr">MCQ-Single Response</option>
<option value="mcqmr">MCQ-Multiple Response</option>
<option value="num">Numerical</option>
<option value="tim">Temporal</option>
<option value="lat">Survey Site - Latitude</option>
<option value="lng">Survey Site - Longitude</option>
<option value="temp">Survey Site - Temporal</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label> </label>
<input type="text" title="Name should only contain letters or numbers" class="form-control"
name="question-{{ loop.index }}" value=" Question of {{ x }}" pattern="[a-zA-Z0-9_ ]+" required>
</div>
</div>
</div>
{% if loop.index % 3 == 0 %} </div><p> </p><p> </p><div class="row"> {% endif %}
<input type="hidden" name="title-{{ loop.index }}" value= {{x}}>
{% endfor %}
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<input type="hidden" name="filename" value= {{filename}}>
<input type="hidden" name="numofField" value= {{numofField}}>
<button class="btn btn-primary" type="submit" value="Update">Submit</button>
</div>
</div>
</div>
</form>
I would like to include an option the user to choose the number of variables he/she wants to choose. Similar to the e-commerce sites or photo albums, they generally give you an option to "show 25" at a time, and give you the option of changing that to "show 50", "show 100", or "show all" in order to allow the user have the control in the amount of clutter they will be able to navigate through in the page. I could find few examples like datatables.js but they only work on tables. I could not find a way how to go about it?
If you access to javascript you can write logic something like this.
let container = document.getElementById('container');
for (let i=0; i<200; i++) {
let div = document.createElement('div');
div.className = 'box';
container.appendChild(div);
}
var items = document.getElementsByClassName('box');
function show(howMany) {
showAll();
let count = parseInt(howMany);
for(let i = 0; i<items.length;i++){
if(i<count){
continue
} else {
items[i].style.display = 'none';
}
}
}
function showAll() {
for(let i = 0; i<items.length;i++){
items[i].style.display = 'inline-block';
}
}
.box{
display: inline-block;
height: 25px;
width: 25px;
background: tomato;
margin-right: 4px;
}
<button onclick="show('50')">show 50</button>
<button onclick="show('100')">show 100</button>
<button onclick="showAll()">show all</button>
<div id="container"></div>
I'm working on my first webapp. I need a simple form for the user to submit a few values. I got it working, but I would like the data entry fields to be on a row instead of in a column.
You can see bootstrap used in the snippets below. I don't think that is involved because the fields render in the same locations without using it.
base.html:
{% extends 'bootstrap/base.html' %}
{% block title %}
...
{% endblock %}
{% block navbar %}
...
{% endblock %}
{% block content %}
<div class="container">
...
{# application content needs to be provided in the app_content block #}
{% block app_content %}{% endblock %}
</div>
{% endblock %}
forms.py:
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, IPAddress, NumberRange, length
class SnmpQueryForm(FlaskForm):
ip = StringField('IP Address', validators=[IPAddress()])
mask = IntegerField('Mask bits',
validators=[DataRequired(),
NumberRange(22, 32)]
)
snmpcmstr = StringField('Community String',
validators=[DataRequired(),
length(max=20)]
)
submit = SubmitField('Submit Query')
template.html:
{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block app_content %}
<h1>Enter SNMP Query Information</h1>
<form action="", method="post">
<div class="row">
<div class="col-md-2">
{{ wtf.quick_form(form) }}
</div>
</div>
</form>
<br>
<br>
<div class="container">
...
Here is the result:
I would like the three fields to be on the same line (in the same row). Any suggestions?
Thank you
Just to add the solution I used for posterity:
All I had to do was change Lakindu's POC code to:
<div class="col-md-4">
<div class="form-group">
{{wtf.form_field(form.ip, class="form-control", placeholder="Enter IP") }}
</div>
</div>
for each input field and add:
<div class="col-md-4">
<div class="input submit">
<input type="submit" value="Submit">
</div>
</div>
for the submit button.
Thank you for the quick help.
This is a proof of concept of what you trying to achieve.
You can use col-md-4 in a row and a container class in order to get three input fields to a single row.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<form action="" , method="post">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>IP address</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Mask bits</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Community string</label>
<input type="text" class="form-control">
</div>
</div>
</div>
</div>
</form>