django search autocomplete not working - python

I am trying to use autocomplete for search but I am getting this error "Uncaught TypeError: $(...).autocomplete is not a function".I have already included jquery library
<head>
<link rel="stylesheet" href="{% static 'styles.css' %}">
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="{% static 'script.js' %}"></script>
<title>{% block title %}Home{% endblock %}</title>
<script>
$(document).ready(function() {
$( "#search_text" ).autocomplete({
source: "/item_search/",
minLength: 2,
});
});
</script>
</head>
<body>
<div id='cssmenu'>
<ul>
<li class='menus'><span>Home</span></li>
<li class='menus'><span>Logout</span></li>
<li id="input" style="padding:11px;float:right;">
<form name="myform" method="GET" action="{% url 'search' %}">
<input type="text" name="search" id="search_text" placeholder="Search"/>
</form>
</ul>
</div>
views.py,
def item_search(request):
book_name = request.GET.get('search')
if book_name is not None:
rows = Add_prod.objects.filter(book__icontains=book_name)
results = [ x.book for x in rows ]
return HttpResponse(json.dumps(results))

Actually I think you are using two jquery remove this one
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

For autocomplete to work, you need to have have jQuery UI library included in your head.
You can download it from here -> https://jqueryui.com/download/all/

Related

Getting Image from image field to views.py model

I am making a social media site in Django. I have a page for making a new post. It has a form with a file field to take an image upload. I want to get the image in views.py to save in the database. In the image variable, a string is getting saved with the name of the image. Also, I don't want to use any external form like forms.py. Here I have also tried request.FILES["image"] but it returned an empty dict.
Views.py
def newpost(request):
if request.method == "POST":
image = request.POST.get("image")
caption = request.POST.get("caption")
post = Post(Image=image,Caption=caption,Owner=request.user.username)
post.save()
return redirect("/")
return render(request,"newpost.html")
newpost.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spark X- New Post</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/newpost.css' %}">
<script class="jsbin" src="{% static 'js/jquery.js' %}"></script>
<link rel="icon" href="{% static 'images/favicon123.png'%}" type="image" sizes="16x16" class="favicon">
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</head>
<body>
<div class="header">
<span class="topband">
<img src="{% static 'images/back icon.png'%}" class="topicon">
</span>
<div class="logoholder">
<p class="logotext">New Post</p>
</div>
</div>
<div class="mainarea">
<form action="" method="post">{% csrf_token %}
<input type="file" name="image" id="image" accept="image/*" class="imageUpload" onchange="readURL(this);"/>
<label for="image"><img src="{% static 'images/camera icon.png' %}" class="cameraIcon" id="blah"></label>
<input type="text" name="caption" placeholder="Caption... " class="caption">
<button type="submit" class="submit">Post</button>
</form>
</div>
</body>
</html>
models.py
class Post(models.Model):
Id = models.AutoField(primary_key=True)
Image = models.ImageField(upload_to="Posts")
date = models.DateTimeField(auto_now=True)
Caption = models.TextField()
Your help will really be appreciated.
I have figured it out. Just used request.FILES["image"] and added enctype="multipart/form-data" in form and it worked.

FLASK BuildError Python

I cannot find what is wrong with my Flask app. I keep getting werkzeug.routing.BuildError: Could not build URL for endpoint 'mark_report'.
Here is /index
<!DOCTYPE html>
<html> <head>
<title>Title</title>
<link rel="stylesheet" href="../static/css/style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 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.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/scripts.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> </head> <body>
{% block content %}
{% endblock %} </body> </html>
Here is our main page
{% extends "index.html" %} {% block content %} <div class="container"> <div class="spacer">
</div> <div class="row header-row">
<h1>EMS Suite</h1> </div> <div class="row">
<div class="col-md-5">
<ul class="list-group">
<li class="list-group-item li-custom"><h3>Mark Report</h3></li> </ul>
</div>
<div class="col-md-7">
{% block page_content %}
{% endblock %}
</div> </div> <nav class="navbar navbar-default navbar-fixed-bottom footer">
<div class="container-fluid">
</div> </nav> </div> {% endblock %}
Here is the route, there is an HTML page named mark_report.html in our template folders.
#app.route('/mark_report')
def mark_report():
return render_template('mark_report.html')
I made the mistake of having the below if statement above my routes.... Thank you everyone
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)

How to add a datepicker into Django ModelFrom?

These are my scripts -
models.py
from django.db import models
class Leave(models.Model):
...
from_date = models.DateField()
to_date = models.DateField()
def __str__(self):
return self.name
I wanted to have datepickers for the above DateField(s).
This is my form template:-
{% extends "base.html" %}
{% block content %}
<div class="container">
<h3> Fill out the form please! </h3>
<h4>
<form action="." role="form", method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type = "submit">Submit</button>
</form>
</h4>
</div>
{% endblock %}
So far, what i have done -
I have included this in my base.html.
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>
In my forms.py as I'm using ModelForms, I have included this code -
class LeaveRequestForm(ModelForm):
class Meta:
fields = ("from_date", "to_date")
model = Leave
widgets = {
'from_date' : DateInput(attrs={'class': 'datepicker'}),
'to_date' : DateInput(attrs={'class': 'datepicker'}),
}
But no datepicker is being reflected in my html template. I have read many other question related to this but couldn't understand. Hope, anyone explains me in detail.
base.html
...
<html>
<head>
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
...
</head>
I think your code is correct. However, from your comment it looks like you're using Bootstrap. You need to import Jquery BEFORE bootstrap.min.js and not after. If you have a javascript error in your page, it will prevent the datepicker from working.

Webpack for serving JS per Flask Application

I have a Flask application I have built locally and have hit the wall as to having javascript with npm packages being able to be used because I am consuming REST APIs and using jQuery per my application. I followed the advice here and have Webpack working.
I ran the command npm run watch
webpack --progress -d --config webpack.config.js --watch
0% compiling
Webpack is watching the files…
Version: webpack 2.1.0-beta.21
Time: 4836ms
Asset Size Chunks Chunk Names
bundle.js 5.97 MB 0 [emitted] main
[366] ./js/index.js 15.3 kB {0} [built]
+ 366 hidden modules
So now I have webpack working with my index.js file and I have the Flask app being served using gunicorn and Docker on 5000.
Everything is working, but my JS is still unresponsive in my Flask application.
Does anyone know what I do to have my index.js file to work per this Flask app with these components I have, or what I am doing incorrectly here?
Here is my html template, rendering just fine. Just not any Javascript:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description"
content="{% block meta_description %}{% endblock %}">
<title>{% block title %}{% endblock %}</title>
<link
rel="stylesheet"
href="{{ url_for('static', filename='styles/vendor/bootstrap.min.css') }}">
<link
rel="stylesheet"
href="{{ url_for('static', filename='styles/main.css') }}">
<link
rel="stylesheet"
href="{{ url_for('static', filename='styles/style.css') }}">
<link
rel="stylesheet"
href="{{ url_for('static', filename='styles/watson.css') }}">
<link
rel="stylesheet"
href="{{ url_for('static', filename='styles/vendor/font-awesome.min.css') }}">
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="{{ url_for('page.home') }}">
</a>
</div>
</div>
</nav>
<main class="container">
<div class="md-margin-top">{% block heading %}{% endblock %}</div>
{% block body %}{% endblock %}
</main>
<footer class="footer text-center">
<div class="container">
<ul class="list-inline">
<li class="text-muted">2018</li>
<li>NMT</li>
<li>How it works</li>
</ul>
</div>
</footer>
<script
src="{{ url_for('static', filename='scripts/vendor/bootstrap.min.js') }}">
</script>
<script src="{{ url_for('static', filename='js/bundle.js') }}"></script>
<script src="{{ url_for('static', filename='node_modules/watson-developer-cloud/v2.js') }}"></script>
<script src="{{ url_for('static', filename='js/index.js') }}"></script>
</body>
</html>
The parts involved in the question: https://jsfiddle.net/cgnws2u3/3/
Error Logs
I updated filepath and now get this per my js files I am trying to link to my project:
Uncaught ReferenceError: require is not defined
at v2-generated.ts:17
Make sure that your Flask project structure contains static folder as per Flask documentation.
According to the relative bundle.js file path in index.html template, your static directory should contain js directory. Make sure you have it there after using webpack and it contains your bundle.js, index.js and the rest of files mentioned in your template.

Django template {% include not working

I'm new to Django. I'm having problem including a sub-template in a main template. The directory structure of my project is attached in the snapshot. I removed the default views.py and created my own folder named "views" and put my views in it. Here is what I've done:
1. app/views/__init__.py
from .home import *
2. app/views/home.py
from django.shortcuts import render
def index(request):
return render(request, 'home.html')
3. app/templates/home.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Administrator Section
</title>
<link type="text/css" rel="stylesheet" href="{% static "css/common.css" %}"/>
<link type="text/css" rel="stylesheet" href="{% static "css/theme/transdmin.css" %}"/>
<link type="text/css" rel="stylesheet" href="{% static "css/login.css" %}"/>
<script type="text/javascript" src="{% static "js/jquery-1.10.2.js" %}"></script>
<script type="text/javascript" src="{% static "js/common.js" %}"></script>
<script type="text/javascript" src="{% static "js/login.js" %}"></script>
</head>
<body>
<div>
<div id="wrapper" class="ys-adminform">
{% include "includes.header_logo.html" %}
<form id="form-login" class="admin-section-form frm">
<div class="header">
<br/>
<h1>Login</h1>
<br/>
</div>
<div class="content">
<div class="form-row">
<input name="email" class="input" placeholder="Email" type="text"/>
<div class="user-icon"></div>
</div>
<div class="form-row">
<input name="password" class="input password" placeholder="Password" type="password"/>
<div class="pass-icon"></div>
</div>
</div>
<div class="footerlogin">
<input class="button" name="btn-login" value="Authenticate" type="button"/>
<div class="message" style="font-weight: bold; padding-top:16px;"> </div>
</div>
</form>
</div>
</div>
{% include "includes.footer.html" %}
</body>
</html>
The problem is include is not adding content from the sub-views.
I understand it could be a path problem but I tried various options like:
{% include "includes.header_logo.html" %}
{% include includes.header_logo.html %}
{% include "includes/header_logo.html" %}
{% include "templates.includes.header_logo.html" %}
{% include "app.templates.includes.header_logo.html" %}
etc.
You have to use directory slashes (/), not dots (.)
For example:
{% include "includes.footer.html" %}
becomes this:
{% include "includes/footer.html" %}
As suggested by Leistungsabfall, "includes/footer.html" works. The header was not working because it had:
This line must be crashing and because of which header was not working.
Simply add template folder with slash .... like
{% include "blog/footer.html" %}

Categories