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.
Related
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.
*I am having trouble in my index.html file. {% extends 'base.html' %} works. But everything b/w
{% block content %}{% endblock content %} doesn't execute. Here are my files.
views.py:-*
from django.shortcuts import render
def index(request):
return render(request, 'main/index.html')
base.html:-
<!doctype html>
{%load static %}
<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="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<title>To Do App</title>
</head>
<body>
<div>
<nav class=" navbar fixed-top navbar-dark bg-dark">
<a class="navbar-brand" href="/">To Do App</a>
</nav>
<div class="container">
{% block content %}
{% endblock content %}
</div>
</div>
</body>
</html>
index.html:-
{% extends 'base.html'%}
{% block content %}
<div class="row">
<div class="col">
<h2>Add Item</h2>
</div>
</div>
{% endblock content %}
All it shows is a navbar of dark color saying To Do App
I also tried adding advanced things like form but it didn't work so then i added this heading saying Add Item. And guess what it doesn't work
When I inspect elements in browser I can see your Heading "Add Item". The only problem was that the whole <div class="container">...</div> was hidden behind nav bar. And the reason was CSS.
Adding something like margin-top: 56px to .container may solve the problem.
Based on documentation you must use only 'endblock' tag when you are closing tag.So you must replace {% endblock content %} with {% endblock %}.
migrations.CreateModel(
name='BasketballScore',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('match_played', models.IntegerField(default='0')),
('lose', models.IntegerField(default='0')),
('win', models.IntegerField(default='0')),
('points', models.IntegerField(default='0')),
('team', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teams_basketball', to='Schedule.Team')),
],
),
This is the portion from my migration folder, i think this is confirming that my BasketballScore model is migarted fine.
class BasketballScore(models.Model):
team = models.ForeignKey(Team, related_name='teams_basketball', on_delete=models.CASCADE)
match_played = models.IntegerField(default='0')
lose = models.IntegerField(default='0')
win = models.IntegerField(default='0')
points = models.IntegerField(default='0')
This is the actual model of BasketballScore.
class BasketballScoreView(generic.ListView):
context_object_name = 'matches'
template_name = 'Schedule/basketball_score.html'
queryset = BasketballScore.objects.all()
def get_queryset(self):
return BasketballScore.objects.all().order_by('-points')
This is the corresponding class BasketballScoreView in views.py.
{% extends 'Schedule/base.html' %}
{% block content %}
<div class="container">
<p><button onclick="window.location='{% url 'index' %}'" class="btn btn-default">Go Back</button></p>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<tr>
<th>Teams</th>
<th>Match</th>
<th>Win</th>
<th>Lose</th>
<th>Points</th>
</tr>
{% for match in matches %}
<tr>
<td>
<div style="width='100';height='20'"><img src="{{ match.team.image.url }}"></div>
{{match.team}}
</td>
<td><div class="text-center">{{match.match_played}}</div></td>
<td><div class="text-center">{{match.win}}</div></td>
<td><div class="text-center">{{match.lose}}</div></td>
<td><div class="text-center">{{match.points}}</div></td>
</tr>
{% endfor %}
</table>
</div>
</div>
{% endblock %}
Now this is the basketball_score.html page.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.horizontal { display: inline; background-color: lightgray; }
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Schedule</title>
{% load static %}
<!-- <link rel="stylesheet" href="{% static 'Schedule/css/bootstrap.css' %}" />
<link rel="stylesheet" href="{% static 'Schedule/css/style.css' %}" /> -->
{% block title %}
{% endblock %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.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>
<body>
{% block content %}
{% endblock %}
</body>
<!-- <script src="{% static 'Schedule/js/calendar.js' %}"></script> -->
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script>
var csrf_token = '{{ csrf_token }}'
</script>
</html>
Now the above code is base.html from which i have extended basketball_score.html. So when i am clicking on the Score Table button, which is taking me to the basketball_score.html page, except the table head that is th portion , nothing is displaying , that is no team name etc. Now i am adding the corresponding urls.py :
path('match/basketball_score/', views.BasketballScoreView.as_view(), name='basketball_score'),
Any help will be appreciated! :)
Make sure you actually have any BasketballScore objects in your database.
I am trying to make a base.html template and inserting a css file in the header. in the page it includes all the styling by it does not do any styling when the link the other page is pressed.
I have two files extending base.html one color_choose.html the other statistics.html which have the exact same lines for linking files. color_choose.html works and it is the first page that opens when navigated and the other is statistics.html
here is the base.html:
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>ColorStore</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
{% block styles %} {%endblock%}
</head>
<body>
<div id="ColorFavor">
<div style="float: right;">
<h2 id="title" class="page-name">Color Picker</h2>
</div>
</div>
{% block navigation %}
{% endblock %}
{% block display %}
{% endblock %}
{% block modal %}
{% endblock %}
{% block scripts %}
{% endblock %}
</body>
</html>
here is the urls.py in the app file:
from django.urls import path
from . import views
urlpatterns = [
path('', views.ColorPageView.as_view(), name='color'),
path('statistics/',views.StatsPageView.as_view(), name='statistics'),
this is the file css is applied and is also the same text in the other file:
{% extends 'base.html' %}
{% block styles %}
<link rel="stylesheet" href="static/styles/main.css" type="text/css">
{% endblock %}
And this is the part in the settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
If I am missing anything I will edit this post as soon as possible, just leave a comment for it.
You are missing a slash '/' before 'static/...'
<link rel="stylesheet" href="/static/styles/main.css" type="text/css">
Your template should have {% load static %} and you should refer to the stylesheet either as /static/styles/main.css or (preferably) you should use the macro "{% static styles/main.css %}"
See the django doc here.
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/