How to get drag & drop operational in Django - python

I'm looking to use a drag-n-drop feature for updating a table in my Django model.
I need to be able to drag items (a list of model objects) between 3 baskets and update the item's basket type in the model. My model contains food items and the status of these items. So the food.names will be the items dragged and 3 baskets are the food.status: 'don't have', 'have', 'need to buy'. Just like this example: https://www.javascripttutorial.net/sample/webapis/drag-n-drop-basics/.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#div1, #div2, #div3 {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<h2>Drag and Drop</h2>
<p>Drag the items back and forth between the three div elements.</p>
{% for row in all_food %}
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
{% if row.status_type == 'have'%}
<ul>
<li>{{row}}
</ul>
{% endif %}
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
{% endfor %}
</body>
</html>
The code above comes out as 33 boxes with the items in the for loop scattered among the boxes.
I mainly use Python and don't have much experience working with front end code. What can I try next?

Related

How can I insert data into the database using django form?

I am trying to use django form to insert some information into the database, but the insert is now working properly.
This is for form page with some inputs that I am using.
<!DOCTYPE html> <html lang="en">
<head>
<!-- /Css -->
<link rel = "stylesheet" type = "text/css" href = "../static/survey.css" />
<!-- /Css -->
<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>Preencha a pesquisa de satisfação</title>
<style>
* {
box-sizing: border-box;
}
input[type=submit] {
background-color: #4CAF50;
color: white;
padding: 10px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
float: right;
}
input[type=submit]:hover {
background-color: #45a049;
}
.col-25 {
float: left;
width: 50%;
margin-top: 6px;
}
.col-75 {
float: left;
width: 100%;
margin-top: 5px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
</style>
<!-- /Fonts -->
<link href='https://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet'> <link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900" rel="stylesheet">
<!-- /Fonts -->
</head>
<body>
<h2>Pesquisa de satisfação</h2>
<p>Avalie a sua experiência em nosso restaurante e nos ajude a melhor o atendimento.</p>
<div class="container">
<h2>{{ note }}</h2>
<form class="formSurvey" action="{% url 'servicesurvey' %}" method="post">
{% csrf_token %}
{{ surveyform }}
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</div>
<div>
Voltar
</div>
</body> </html>
view.py with the function servicesurvey that calls the POST method and return the render.
from django.shortcuts import render
from .forms import SurveyForm
from .models import Survey
def home(request):
return render(request, 'survey/home.html')
def servicesurvey(request):
if request.method == 'POST':
filled_form = SurveyForm(request.POST)
if filled_form.is_valid():
note = 'Obrigado por responder nossa pesquisa'
new_form = SurveyForm()
return render(request, 'survey/servicesurvey.html', {'surveyform': new_form, 'note':note})
else:
form = SurveyForm()
return render(request, 'survey/servicesurvey.html', {'surveyform':form})
def qrcode(request):
return render(request, 'survey/qrcode.html')
models.py with the 2 inputs that I am trying to save at my database.
from django.db import models
class Survey(models.Model):
aboutTheService = models.CharField(max_length=100)
aboutTheFood = models.CharField(max_length=100)

How to run python code in html page using django

I am learning web development using django framework. I have little trouble in running python code in an html page. I need to iterate through a list of strings which basically contains the paths of images that I want to show in a carousel. I am getting this error "Invalid block tag on line 83: 'with.i', expected 'endblock'. Did you forget to register or load this tag?" in galleryPage.html file when I try to open that page. These are the few lines of code that I've written so far
/views.py/
def galleryPage(request):
from os import listdir
from os.path import isfile, join
ImageList = []
imagePath = "static/images/gallery/"
for f in listdir(imagePath):
temp = join(imagePath, f)
if isfile(temp):
temp = "../" + temp
ImageList.append(temp)
return render(request, "galleryPage.html", {"imageList": ImageList})
/galleryPage.html/
{% extends 'base.html' %}
{% block title %} GALLERY {% endblock %}
{% block slideshow %}
* {box-sizing: border-box;}
body {font-family: Verdana, sans-serif;}
.mySlides {display: none;}
img {vertical-align: middle;}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
#-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
#keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/* On smaller screens, decrease text size */
#media only screen and (max-width: 300px) {
.text {font-size: 11px}
}
{% endblock %}
{% block content %}
<div class="slideshow-container">
{% with.i = 0 %}
<indent>
{{ for image in imageList.0: }}
{% ++i %}
<div class="mySlides fade">
<div class="numbertext"> {% i %} / {{ imageList.size() }} </div>
<img src="{{ image }}" style="width:100%">
<div class="text">Caption Text</div>
</div>
</indent>
{% endwith %}
</div>
<br>
<div style="text-align:center">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<script>
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
{% endblock %}
{% with.i = 0 %}
should be
{% with i=0 %}
Why do you have imageList.0 instead of imageList?
Also, I think you may want to consider combining your current "with" and "for" into one "for" loop like in the docs I posted above:
{% for key, image in imageList %}
<div class="mySlides fade">
<div class="numbertext"> {% key %} / {{ imageList.size() }} </div>
<img src="{{ image }}" style="width:100%">
<div class="text">Caption Text</div>
</div>
{% endfor %}
This way you won't need to increment i yourself and you take away some complexity (and some sources of errors).

Why my paging bootstrap style does not work?

I practice "Flask Web Development"blog article when paging links paging,bootstrap style does not work.But the other can be used.I was using macros import, hope that other places can be common this.Is it necessary to add at import time? .
somebody help me.
this is index.html
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% import '_macros.html' as macros %}
{% block head %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% block scripts %}
{{ super() }}
<script type="text/javascript">
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
})
</script>
{% endblock %}
{% block styles %}
{{ super() }}
<style type="text/css">
body {
background-color: #ffffff;
/*background-color: #F0F0F0;*/
position: relative;
}
.header {
background-color: #FFFFFF;
background-attachment: scroll, fixed;
background-position: top left, top left;
background-repeat: repeat, no-repeat;
background-size: auto, auto 100%;
color: rgba(255, 255, 255, 0.5);
height: 100%;
left: 0;
padding: 8em 4em 0 0;
position: fixed;
text-align: right;
top: 0;
width: 20%;
padding: 0 0 0 0;
}
.img {
background-color: #235F2A;
height: 23.6076%;
width: 61.8%;
margin-top: 14.5924%;
margin-left: 19.1%;
margin-right: 19.1%;
padding: 0 0 0 0;
}
.breadcrumb {
margin-left: 25.28%;
margin-top: 3%;
width: 68.33%;
background-color: #FFFF93;
}
.sketcho {
width: 83.7%;
background-color: #ffffff;
opacity: 1;
margin-left: 7.72%;
margin-top: 8.5%;
}
.container-fluid {
margin-left: 20%;
padding-left: 0px;
padding-right: 0px;
}
.sketch {
width: 83.7%;
background-color: #ffffff;
opacity: 1;
margin-left: 7.72%;
margin-top: 1%;
}
section {
padding-left: 17px;
padding-right: 17px;
}
.paging {
margin-left: auto;
text-align: center
}
.center {
margin-top: 320px;
height: 35px;
}
.row_button {
width: 35px;
height: 35px;
float: left;
}
</style>
{% endblock %}
{% endblock %}
{% block title %}Index{% endblock %}
{% block page_content %}
<body id="top">
<div class="container-fluid">
{% for Article in Articles %}
<div class="row sketch">
<section id="one">
<header class="major">
{{ Article.head }}
</header>
<p>{{ Article.body }}</p>
<ul class="actions">
<li>
<button type="button" class="btn btn-info">Learn More</button>
</li>
</ul>
</div>
{% endfor %}
<div class="row paging">
{{ macros.pageination_widget(pageination, '.index') }}
</div>
</div>
<script src="{{ url_for('static',filename='js/jquery-3.2.1.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/bootstrap.min.js') }}"></script>
</body>
{% endblock %}
_macros.html
{% macro pageination_widget(pageination, endpoint) %}
<nav aria-label="Page navigation">
<ul class="pageination">
<li {% if not pageination.has_prev %} class="disabled" {% endif %}>
<a href="{% if pageination.has_perv %}{{ url_for(endpoint, page=pageination.page - 1, **kwargs) }}{% else %}#{% endif %}">
«</a>
</li>
{% for page in pageination.iter_pages() %}
{% if page %}
{% if page == pageination.page %}
<li class="active">
{{ page }}
</li>
{% else %}
<li>{{ page }}</li>
{% endif %}
{% else %}
<li class="disabled"></li>
{% endif %}
{% endfor %}
<li {% if not pageination.has_next %} class="disabled" {% endif %}>
»
</li>
</ul>
</nav>
{% endmacro %}
It seems like you have a typo on your class names.
Try <ul class="pagination"> instead of <ul class="pageination">.
You can find the full docs for the classes to use here:
https://getbootstrap.com/docs/3.3/components/#pagination-default

Dynamically increase the height of the div container

I have two div containers for which I have fixed the height and width. One of the containers holds the body of the blogpost and other holds the list of all the posts created. Since, body of a blogpost or list of posts can be larger than the size of their div container. So, I want to dynamically increase container's size when they exceed its size. How can I achieve it either using css or javascript?
css file
body {
background-color:#FFCCFF;
}
#container {
position:absolute;
top:50px;
left:100px;
right:100px;
bottom:50px;
}
#content {
margin-top:20px;
padding:0;
width:70%;
height:550px;
border:1px solid black;
background-color: #282828 ;
color:white;
}
#footer {
width:100%;
height:50px;
border:1px solid black;
}
#rightnav {
position:absolute;
top:18px;
right:20px;
width:275px;
height:550px;
background-color: #282828 ;
}
#rightnav p {
margin:0px 0 10px 0px;
padding:0px;
color:#CCCCFF;
}
#rightnav h2 {
text-align: center;
background-color: #000000;
margin:0;
color:#FF9900;
}
#rightnav a {
text-decoration: none;
}
#posts {
padding:0;
width:80%;
border:1px solid black;
}
#posts h2 {
margin:0;
padding:0;
}
#posts p {
margin:5px;
padding:0;
}
#content a {
text-decoration: none;
background-color: none;
color:black;
}
base.html #every other html files inherit from this base file
{% load staticfiles %}
<html>
<head>
<link rel="stylesheet" href="{% static 'css/base.css' %}" type="text/css">
</head>
<body>
<div id = "container" style="clear:both;">
<div id = "content">
{% block post %}
{% endblock %}
</div>
<div id = "rightnav">
<h2>Popular Posts</h2>
{% block popular_posts %}
{% endblock %}
</div>
</div>
</body>
</html>
post.html #the template which deals with showing posts
{% extends "blog/base.html" %}
{% block post %}
{% load django_markdown %}
<h2>{{post.title}}</h2>
{{ post.body|markdown }}
{% endblock %}
{% block popular_posts %}
{% for post in posts %}
<p>{{ post.title }}</p>
{% endfor %}
{% endblock %}
Adding to Marcanuy's answer, you have to remove the bottom:50px given to the #container div.
And by removing position:absolute from unwanted places will make your css neat. If you want to position your div side by side, you can use display:flex for your parent (#container) div.
EDIT: Have also removed the position:absolute property and have added margin:50px to make your div center-aligned. (You can also use padding property)
Refer : JsFiddle
#container {
position:absolute;
top:50px;
left:100px;
right:100px;
}
#content {
padding:0;
width:70%;
min-height:550px;
border:1px solid black;
background-color: #282828 ;
color:white;
}
#rightnav {
width:275px;
min-height:550px;
background-color: #282828 ;
}
Change your height with min-height, this will make your containers have at least the specified height, then they will grow and fit their content needs.
#rightnav {
min-height:550px;
}
#content {
min-height:550px;
}

How can i include a view function in django template?

I am new in django. So i need a help for including a view function within Template. I am searching but i am tired for finding my expectation. i want to use only django template tag. Would you please help me?
{View.py
def singUpLunch(request):
query_results = Menu.objects.all()
form=SingUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
messages.success(request,'Thanks for your co-operation')
return render_to_response('singUp.html',locals(),context_instance=RequestContext(request))
}
{my model
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField()
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
}
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField() # auto_now_add=True, blank=True default=date.today(),blank=True
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
my Template
{% load url from future %}
{% block content %}
{% if not email %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Log in</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style>
body
{
margin: 0;
padding: 0;
color: #555;
font: normal 12pt Arial,Helvetica,sans-serif;
background:#ffffff url(check2.jpg) repeat-x;
width: 130%;
height: 100%;
position: fixed;
top: 40px;
left: 480px
}
.span3.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5ff;
border: 1px solid #e3e3e3;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body>
<head><div class='page-header pagination-centered'><img src=/static/logo.png class='img-rounded pagination-centere' /></div> </head>
{{ state }}
<div class="span3 well" style="height: auto;margin-left: 1.7%;width: 30%;">
<h2>Please Login
New User: &nbsp<a href="/signup/">
SignUp</a></h2>
<div class="leftpane">
<form action="" method="post"> {% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
Email:
<input type="text" name="email" value="{{ email}}" /><br /><br />
password:
<input type="password" name="password" value="" /><br /><br />
<input type="submit" value="Log In" />
</form>
</div>
<div class="aboutus_portion">
</div>
</div>
<!-- <div id="rightcontent">
<li class=" dir"><h3>Admin</h3> </li>
</div>
-->
</body>
</html>
{% else %}
{% include 'singUpLunch' %} # here i want to call the view singUpLunch function
{% endif %}
{% endblock %}
You can see this Django custom template tags
Django expects template tags to live in a folder called 'templatetags' that is in an app module that is in your installed apps...
/my_project/
/my_app/
__init__.py
/templatetags/
__init__.py
my_tags.py
#my_tags.py
from django import template
register = template.Library()
#register.inclusion_tag('other_template.html')
def say_hello(takes_context=True):
return {'name' : 'John'}
#other_template.html
{% if request.user.is_anonymous %}
{# Our inclusion tag accepts a context, which gives us access to the request #}
<p>Hello, Guest.</p>
{% else %}
<p>Hello, {{ name }}.</p>
{% endif %}
#main_template.html
{% load my_tags %}
<p>Blah, blah, blah {% say_hello %}</p>
The inclusion tag renders another template, like you need, but without having to call a view function. Hope that gets you going.

Categories