I have a page where the users can add a new mco number, when the user click on the Add mco button, it will retrieve the id as shown below:
but when the user add the new mco number and click on the submit button, it will create another row and not update into the id database as shown below, why is that so and how do I solve this issue?
views.py
#login_required()
def AddMCO(request, id):
photo = get_object_or_404(Photo, id=id)
if request.method == "POST":
form = AddMCOForm(request.POST)
if form.is_valid():
mcoNum = form.cleaned_data['mcoNum']
form.save()
return redirect('ViewMCO')
else:
form = AddMCOForm()
context = {
"form": form,
"photo": photo
}
return render(request, 'AddMCO.html', context, )
forms.py
class AddMCOForm(forms.ModelForm):
mcoNum = forms.CharField(
label='Enter MCO Number',
widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Please enter MCO Number here..'
}
)
)
class Meta:
model = Photo
fields = ("mcoNum",)
def __init__(self, *args, **kwargs):
super(AddMCOForm, self).__init__(*args, **kwargs)
self.fields['mcoNum'].widget.attrs.update({'class': 'form-control', 'placeholder': 'MCO Number'})
self.fields['mcoNum'].label = ''
self.fields['mcoNum'].help_text = ''
AddMCO.html
<!DOCTYPE html>
<html>
<head>
<script>
$(function () {
$("#datetimepicker1").datetimepicker();
});
</script>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>SCS Add MCO</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!-- Font Awesome -->
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- Moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script>
<!-- Tempus Dominus Bootstrap 4 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script>
</head>
<body class="m-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-4">
<h3>Add MCO Number</h3>
Go Back
<div class="card" style="width: 400px">
<form method="post">
{% csrf_token %}
<div class="form-group m-3">
<br>
{{ form.as_p}}
</div>
<button type='submit' class="btn btn-primary m-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
models.py
class Photo(models.Model):
STEP1 = "Reception"
STEP2 = "Launching"
STATUS = (
(STEP1, 'Reception'),
(STEP2, 'Launching'),
)
Datetime = models.DateTimeField(auto_now_add=True)
mcoNum = models.TextField() #mcoNum stand for MCO number
serialno = models.TextField() # serialno stand for serial number
partno = models.TextField() # partno stand for part number
reception = models.TextField()
Customername = models.TextField() #Custoner Name
status = models.CharField(max_length=20, choices=STATUS, default=STEP1, editable=False)
def __str__(self):
return self.reception
you are not passing the instance to the form assuming the photo model has addMCO Form as model form of course.
#login_required()
def AddMCO(request, id):
photo = get_object_or_404(Photo, id=id)
if request.method == "POST":
form = AddMCOForm(request.POST, instance=photo)
if form.is_valid():
mcoNum = form.cleaned_data['mcoNum']
form.save()
return redirect('ViewMCO')
else:
form = AddMCOForm(instance=photo)
context = {
"form": form,
"photo": photo
}
return render(request, 'AddMCO.html', context, )
You have not mentioned Django version and which db is used.
Check if this can help you. Django not updating database
Related
So, I have an image classification app that is meant to display an uploaded image along with the prediction or class. I have two template files: index.html and results.html. The flask app is meant to render the result.html when a post request is made, however, it only displays the alt text.
Below is my flask app:
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/')
def index():
return render_template('index.html')
#app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
file = request.files.get('file')
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if not file:
return
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
img_bytes = file.read()
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#image_url = url_for('uploaded_file', filename=filename)
class_id, class_name, score = get_prediction(input_img= img_bytes)
return render_template('result.html', class_id=class_id, class_name=class_name, score=score, filename=filename)
#app.route('/display/<filename>')
def display_image(filename):
return redirect(url_for('static', filename='uploads/' + filename), code=301)
In my template file i.e. results.html, I have the following code to display the uploaded image alongside the prediction but it only shows the prediction without an image:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<link rel="stylesheet" href="/static/style.css">
<title>Prediction using ResNet</title>
</head>
<body class="text-center">
<form class="form-signin" method=post enctype=multipart/form-data>
<img class="mb-4" src="{{ url_for('display_image', filename=filename) }}" alt="no image found" width="300" height="300">
<h1 class="h3 mb-3 font-weight-normal">Results</h1>
<h5 class="h5 mb-3 font-weight-normal">Prediction: {{ '{} ({:.4f})'.format(class_name, score) }}</h5>
<h5 class="h6 mb-3 font-weight-normal">Prediction ID: {{ class_id }}</h5>
<p class="mt-5 mb-3 text-muted">Built using Pytorch, Flask and Joy</p>
</form>
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</body>
</html>
This displays the alt text i.e no image found. Kindly assist with suggestions. Thanks.
I am a beginner to Django and unable to populate the items from my database table to <option></option>.
From models.py:
from django.db import models
from django.db.models.fields.related import ForeignKey
# Create your models here.
class Tbl_Category(models.Model):
cat_Id = models.AutoField(primary_key=True)
cat_Name = models.CharField(max_length=20, unique=True)
# def __str__(self):
# return [self.cat_Id, self.cat_Name]
class Tbl_Item(models.Model):
item_Id = models.AutoField(primary_key=True)
item_Name = models.CharField(max_length=30, unique=True)
cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE)
item_Price = models.IntegerField()
From views.py:
from django.shortcuts import render
from orderapp.models import Tbl_Item
# Create your views here.
def displayMain(request):
return render(request,'index.html')
def ct(request):
options = Tbl_Item.objects.filter(cat_Idf=1)
context = {'alloptions' : options}
return render(request, 'index.html', context)
From index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" href="{% static 'css.css' %}">
<title>DATA COLLECTION</title>
</head>
<body>
<div class="container">
<div class="order-screen">
<div class="element">
<label for="coffee-tea">Coffee-Tea</label>
<select name="coffee-tea" id="coffee-tea">
{% for opt in alloptions %}
<option value="{{opt.item_Id}}">{{opt.item_Name}}</option>
{% endfor %}
</select>
</div>
<div class="cart-screen">CART-SCREEN</div>
</div>
</body>
</html>
I assure you that my database connection is working absolutely fine and there was no problem while running makemigrations and migrate commands. My tables contain values that I have hardcoded. Please guide me with what is wrong with my approach. Thank you.
If I understand you question correctly you want to have a dropdown for different options in a form. In Django this would be done on the model with choices
example
OWNERSHIP=[
('current owner', 'Current Owner'),
('past owner','Past Owner'),
]
class Post(models.Model):
title = models.CharField(max_length=100)
ownership = models.CharField(max_length=100, choices=OWNERSHIP)
then just render the form field as {{ form.ownership }} and it will give you a dropdown
I have a page where it allows the user to enter the reception number, so when the user enter the reception number, it should verify with the database if the reception number exist, but i am having this error: 'verifyForm' object has no attribute 'reception'. How do I solve this error?
Updated with traceback error
views.py
#login_required()
def verifydetails(request):
if request.method == 'POST':
#Customername = request.GET['Customername']
form = AddForm(request.POST or None)
if form.reception == Photo.reception:
messages.success(request, 'Both Reception and customer name match')
return redirect('AddMCO')
else:
messages.success(request, 'Both Reception and customer do not match')
return redirect('verifydetails')
else:
form = AddForm()
return render(request, 'verifydetails.html', {'form': form, })
forms.py
class verifyForm(forms.Form):
reception = forms.CharField(label='',
widget=forms.TextInput(
attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'}))
class meta:
model = Photo
fields = ('reception')
verifydetails.html
<!DOCTYPE html>
<html>
<head>
<script>
$(function () {
$("#datetimepicker1").datetimepicker();
});
</script>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>SCS verify details</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!-- Font Awesome -->
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- Moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script>
<!-- Tempus Dominus Bootstrap 4 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script>
</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 %}
<body class="m-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-4">
<h3>Verify Details</h3>
Go Back
<div class="card" style="width: 400px">
<form method="post">
{% csrf_token %}
<div class="form-group m-3">
<label>Reception:</label>
<br>
{{ form.reception}}
</div>
<button type='submit' class="btn btn-primary m-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
traceback error in my code is this:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/verifydetails/
Django Version: 2.2.20
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']
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:
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "E:\Role_based_login_system-master\account\views.py" in verifydetails
496. if form.reception == Photo.reception:
Exception Type: AttributeError at /verifydetails/
Exception Value: 'verifyForm' object has no attribute 'reception'
form = AddForm(request.POST or None) This line says that form can also be None if object is not found.
You're trying to run this line if form.reception == Photo.reception: before checking if form is valid or None.
To solve this problem, do something like:
if form:
if form.reception == Photo.reception:
........
else(optional):
print("the object doesn't exist")
Change form.reception to form.cleaned_data["reception"]
registration and login page is working properly but mine count of likes is not showing in django... I don't know why... Can somebody help me to find this error... It will be the great help... Thank You!!
1.Views.py
from django.shortcuts import render, get_object_or_404, redirect
from datasecurity.models import Post
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def likes(request, pk):
post=get_object_or_404(Post, pk=pk)
post.likes.add(request.user)
return HttpResponseRedirect(reverse('datasecurity:datasecurity'))
def datasecurity(request):
allPosts= Post.objects.all()
context={'allPosts': allPosts}
def __init__(self, *args, **kwargs):
stuff = get_object_or_404(Post, id = self.kwargs['pk'])
total_likes = stuff.total_likes()
context['total_likes'] = total_likes
return render(request, 'datasecurity/data.html',context=context)
def blogHome(request, slug):
post=Post.objects.filter(slug=slug).first()
context={"post":post}
return render(request, "datasecurity/blogHome.html", context)
2.Urls.py
from django.conf.urls import url
from . import views
app_name = 'datasecurity'
urlpatterns = [
url(r'^$', views.datasecurity, name="datasecurity"),
url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'),
url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"),
]
3.models.py
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
sno=models.AutoField(primary_key=True)
title=models.CharField(max_length=255)
author=models.CharField(max_length=14)
slug=models.CharField(max_length=130)
timeStamp=models.DateTimeField(blank=True)
content=RichTextField(blank=True, null=True)
img = models.ImageField(blank=True, null=True, upload_to="dataimage/")
likes = models.ManyToManyField(User)
#property
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + " by " + self.author
4.data.html
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link
href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900"
rel="stylesheet"
/>
<meta charset="utf-8">
<title></title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/datasecurity.css' %}">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=PT+Sans&display=swap" rel="stylesheet">
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/cover/">
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v9.0" nonce="noEcH88O"></script>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v3.2"></script>
</head>
<body>
<!-- End header -->
<div id="page-wraper">
<!-- Sidebar Menu -->
<div class="responsive-nav">
<div class="top-navbar">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<marquee><ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" href="{% url 'careforallapp:base' %}">Home</a></li>
</ul></marquee>
</div>
</div>
</nav>
</div>
<section class="section about-me" data-section="section1">
<div class="container">
<div class="section-heading">
<h2>Welcome to Data Security</h2>
{% for post in allPosts %}
<div class="line-dec"></div>
<span
>This is a Bootstrap v4.2.1 CSS Template for you. Edit and use
this layout for your site. Updated on 21 May 2019 for repeated main menu HTML code.</span
>
</div>
<div class="left-image-post">
<div class="row">
<div class="col-md-6">
<div class="left-image">
{% if post.img %}
<img src="{{ post.img.url }}" alt="" />
{% endif %}
</div>
</div>
<div class="col-md-6">
<div class="right-text">
<h4>{{post.title}}</h4>
<h6>Article by {{post.author}}</h6>
<h2>{{post.datetime}}</h2>
<p>
{{post.content|safe | truncatechars:280}}
</p>
<form action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">
{% csrf_token %}
<button type="submit" name="post_id" value = "post_id" class="btn"> Like </button> - {{ total_likes }} likes
</form><br><br>
<div class="white-button">
Read More
</div><br>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{% endfor %}
</div>
<div>
</section>
</div>
There is no error when I debug the code .. may be it is logical error .. I really don't know .. can someone help me to find out the error Thank you
Looks like you want to display all posts in your datasecurity view. You have declared a function __init__ inside it for some reason (not even using it, also it's not even in a class as __init__ might imply). Change the view like this:
def datasecurity(request):
allPosts= Post.objects.all()
context={'allPosts': allPosts}
return render(request, 'datasecurity/data.html',context=context)
Now in your template you are using {{ total_likes }} but you haven't passed any such variable in the context. But I notice you have declared a method on your model that does the same so change it to {{ post.total_likes }}.
I'm trying to replicate the live search option as described here https://developer.snapappointments.com/bootstrap-select/examples/ in my Flask application. The minimal example below has the third box hardcoded as in the example and it works as expected.
My actual app uses WTF forms/Jinga2 and I cannot figure out how to modify the Jinga2 code such that the live search would be available in my first SelectField or in the second SelectMultipleField.
Can someone suggest how I can implement a live search using the WTF form/Jinga2 to resemble the working example?
from flask import Flask, render_template, request, session, current_app, flash,redirect, url_for, jsonify
from flask_wtf import FlaskForm
from wtforms import StringField, TextField, SubmitField, SelectField, IntegerField, BooleanField, RadioField, FileField, HiddenField,SelectMultipleField
from wtforms.validators import DataRequired, Length
server = Flask(__name__)
server.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
class simpleForm(FlaskForm):
varlist1 = SelectField('Choose', [DataRequired()], coerce=str)
varlist2 = SelectField('Choose', [DataRequired()], coerce=str)
submitA = SubmitField('Get Stuff')
varlist3 = SelectMultipleField('Choose Test(s):', [DataRequired()], choices=[('', '')])
#server.route('/menu', methods=["post", "get"])
def menu():
form = simpleForm()
vars = ['Option 1','Option 2']
var2list = [['A', 'B', 'C'],['D','E', 'F', 'G'],['1', '2']]
vars3 = ['a','b','c','d']
form.varlist1.choices = vars
form.varlist2.choices = var2list[0]
form.varlist3.choices = [(i, i) for i in vars3]
#form.varlist2.choices = var2list[1]
#form.varlist2.choices = var2list[2]
return render_template('menu.html', form = form)
if __name__ == '__main__':
server.run(debug=True)
Here is a minimal html menu.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</head>
<title>My Application</title>
<body>
<br><br><br>
<form action="{{url_for('menu')}}" method="POST" enctype="multipart/form-data">
<br>
<div>
{{ form.varlist2.label}}
{{ form.varlist2 (class="form-control") }}
<br>
{{ form.varlist3.label}}
{{ form.varlist3 }}
</div>
</form>
<br><br>
<select class="selectpicker" data-live-search="true">
<option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
<option data-tokens="mustard">Burger, Shake and a Smile</option>
<option data-tokens="frosting">Sugar, Spice and all things nice</option>
</select>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js"></script>
<!-- (Optional) Latest compiled and minified JavaScript translation files -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/i18n/defaults-*.min.js"></script>
</body>
</html>
A little late but here is an answer if someone else is having the same issue.
In your Jinja template, you need to replace:
{{ form.varlist2 (class="form-control") }}
with:
<select class="selectpicker form-control" name="varlist2" data-live-search="true">
{% for option in form.varlist2 %}
{{ option }}
{% endfor %}
</select>