I am brand new to AJAX requests and I am still learning Django, but I have a project where the user enters an Elasticsearch query and then we generate a downloadable document (report) for the user.
I have an AJAX request to continuously check on the existence of a file in my form.html file and it doesn't seem to be getting picked up at all. I can tell this because it isn't giving me any alerts and it's just automatically timing out on big requests after ~30 seconds.
I tried to write a temporary fix in my views.py that is basically attempting to do what the javascript in form.html is doing, but A) I feel like this isn't the best method to use in production, B) it doesn't feel like a good use of time to essentially re-invent the wheel, and C) I want the user to get some sort of alert or indication on their end that the report is in progress, and then when it's ready to download.
How can I modify my code to actually perform the AJAX request? Or why does it appear that the AJAX request isn't working?
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('form/', include('audit_tool.urls')),
path('report/', include('audit_tool.urls')),
path('check_progress/', views.check_progress, name='check_progress'),
# path('return_doc/', views.return_doc, name='return_doc'),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
audit_tool/urls.py
urlpatterns = [
path('', views.get_query, name='form'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from docx import Document
import os
import threading
from .forms import QueryForm
from .models import *
#login_required
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
query = form.cleaned_data["query"]
fn = str(time.time()).replace(".", "_") + ".docx"
t = threading.Thread(target=generate_doc, args=(query, fn))
t.start()
return HttpResponseRedirect('/check_progress/')
else:
return HttpResponse("Your query does not appear to be valid. Please enter a valid query and try again.")
else:
form = QueryForm()
return render(request, 'icm_audit_tool/form_template.html', {'form': form})
#login_required
def check_progress(request):
"""
Returns whether document generation is complete or in progress
"""
fn = request["filename"]
file = "/app/created_files/" + fn
while not os.path.exists(file):
time.sleep(10)
if os.path.exists(file):
doc = Document(file)
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename={}'.format(fn)
doc.save(response)
return response
form.html
{% block javascript %}
<script>
var checkInterval = setInterval(isFileComplete, 10000); //10000 is 10 seconds
function isFileComplete() {
$.ajax({
url: '/check_progress/',
type: 'GET',
dataType: 'json',
success: function (data) {
if (data.file_created) {
alert("Your file is ready to download!");
clearInterval(checkInterval);
} else {
alert("Your report is still being created, please hold.");
checkInterval;
}
}
});
}
</script>
{% endblock %}
base_login.html
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<link rel="shortcut icon" href="link/to/company/iconicon.ico" type="image/vnd.microsoft.icon" />
<title>Audit Report Tool</title>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Dept</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="../">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../admin">Admin</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<hr class="mt-0 mb-4">
<img src="{% static "logo.png" %}" alt="Company Logo" align="left"></img>
<img src="{% static "logo.png" %}" alt="Dept Logo" align="right" width="140" height="140"></img>
<h1 align="center"><font size="6"> Audit Report Tool</font></h1>
</div>
</div>
</div>
<body>
<main>
{% block content %}
{% endblock %}
</main>
{% block javascript %}{% endblock %}
</body>
</html>
Related
I am new to Django and am trying to make an online journal, and the server runs fine, but when I press the create button, it does not redirect to the form even though a POST request is being sent. screenshot of the create page. I'm not sure why.
This is the code:
views.py:
from django.shortcuts import render, redirect, get_object_or_404
from ejournal.models import Journal
from ejournal.forms import JournalForm
def make_entry(request):
if request.method == "POST":
entry = JournalForm(request.POST, request.FILES)
if entry.is_valid():
entry.save()
return redirect('list_journals')
else:
entry = JournalForm()
context = {
'entry':entry
}
return render(request, 'ejournal/create.html', context)
def delete_entry(request, id):
entry = get_object_or_404(Journal, id=id)
if request.method == "POST":
entry.delete()
return redirect('list_journals')
context = {
'object':object
}
return render(request, 'journal/delete.html',context)
def list_journals(request):
entries = Journal.objects.all()
context = {
'entries': entries
}
return render(request, 'ejournal/list_journals.html',context)
def journal_detail(request, id):
journal = Journal.objects.get(id=id)
context = {
'journal':journal
}
return render(request, 'journal/journal_detail.html', context)
forms.py
from ejournal.models import Journal
from django.forms import ModelForm
class JournalForm(ModelForm):
class Meta:
model = Journal
fields = ['name','title','text','image']
models.py
from django.db import models
class Journal(models.Model):
name = models.CharField(max_length=20)
title = models.CharField(max_length=50)
text = models.TextField(max_length=1000)
date = models.DateField(auto_now_add=True)
image = models.FileField(upload_to='')
archived = models.BooleanField(default=False)
def __str__(self):
return self.name
base.html
{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>My Online Journal</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{% url 'list_journals' %}">Smart Journal</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'list_journals' %}">LIST ALL</a>
</li>
</ul>
</div>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'make_entry' %}">+ New Journal Entry </a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container" id="app">
{% block content %}
{% endblock %}
</div>
<!-- /.container -->
<!-- Bootstrap core JavaScript -->
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
create.html
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
urls.py
from django.urls import path
from ejournal.views import make_entry, delete_entry, list_journals, journal_detail
urlpatterns = [
path('create', make_entry, name="make_entry"),
path('list_journals', list_journals, name="list_journals"),
path('delete/<int:id>/', delete_entry, name="delete_entry"),
path('journal_detail/<int:id>',journal_detail, name="journal_detail"),
]
You pass the form as the variable entry to your template ejournal/create.html.
Inside this template you use {{ form.as_p }}, but form is undefined. You need to use the variable entry because thats where the form is assigned to.
So your create.html becomes this:
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ entry.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
You're checking if your form is valid by using entry.is_valid(), but your form will always be invalid because you didn't pass the correct form in your template, as described above.
Check with form's action='' attribute like this...
<form method="POST" action="{% url 'make_entry' %}" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
I create program stock management system by using Django. Page of Update_items that create for saving and updating. Program can running but when I will update new data it can't save and update data. It will redirect with same data. I'm not sure whatit's wrong. I am very new so please introduce me.
This is from views.py
from email import header
from multiprocessing import context
from urllib import request
from django.shortcuts import render,redirect
import stockmgmt
from .models import Stock
from .forms import StocksearchForm,StockCreateForm,StockUpdateForm
def home(request):
title = 'ยินดีต้อนรับเข้าสู่ระบบสต็อคสินค้าเซียงกง'
form = 'Welcome: This is the Home Page'
context = {
"title": title,
"test": form,
}
return render(request, "home.html",context)
def list_items(request):
title = 'รายการสินค้า'
form = StocksearchForm(request.POST or None)
queryset = Stock.objects.all()
context = {
"title": title,
"queryset": queryset,
"form":form
}
if request.method == 'POST':
queryset = Stock.objects.filter(category__icontains=form['category'].value(),item_name__icontains=form['item_name'].value(),id_product__icontains=form['id_product'].value(),shop_name__icontains=form['shop_name'].value())
context ={
"form":form,
"header": header,
"queryset": queryset,
}
return render(request, "list_items.html",context)
def add_items(request):
form=StockCreateForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/list_items')
context={
"form":form,
"title":"Add Item",
}
return render(request,"add_items.html",context)
def update_items(request, pk):
queryset = Stock.objects.get(id=pk)
form = StockUpdateForm(instance=queryset)
if request.method == ' POST':
form = StockUpdateForm (request.POST, instance=queryset)
if form.is_valid():
form.save()
return redirect('/list_items')
context = {
'form':form
}
return render(request, 'add_items.html', context)
This is list_items.html
{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<body>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>รายการสินค้า</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/navbar-top-fixed/">
<!-- Bootstrap core CSS -->
<link href ="../../dist/css/bootstrap.min.css" rel ="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="navbar-top-fixed.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">สต็อคสินค้าร้านเซียงกง</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">หน้าแรก <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/list_items">รายการสินค้า</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/add_items">เพิ่มรายการสินค้า</a>
</li>
</ul>
<form class="form-inline mt-2 mt-md-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<main role="main" class="container">
<div class="jumbotron">
<h1>รายการสินค้า</h1>
<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input type="submit" value='Search'/>
</form>
<br>
<table class='table'>
<thead>
<tr>
<th>รายการสินค้า</th>
<th>ประเภทสินค้า</th>
<th>ชื่อสินค้า</th>
<th>รหัสสินค้า</th>
<th>ชื่อร้าน</th>
<th>ราคา/หน่วย</th>
<th>จำนวนที่มีอยู่ในร้าน</th>
</tr>
</thead>
{% for instance in queryset %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{instance.category}}</td>
<td>{{instance.item_name}}</td>
<td>{{instance.id_product}}</td>
<td>{{instance.shop_name}}</td>
<td>{{instance.price}}</td>
<td>{{instance.quantity}}</td>
</tr>
{% endfor %}
</table>
</div>
</main>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<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.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
This is url.py
"""djangoproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from stockmgmt import views
urlpatterns = [
path('', views.home, name='home'),
path('list_items/', views.list_items, name='list_items'),
path('add_items/', views.add_items, name='add_items'),
path('update_items/<str:pk>/', views.update_items, name="update_items"),
path('admin/', admin.site.urls)
]
This is my error in command promopt
In forms.py
from django import forms
from .models import Stock
# Create your forms here
class StockForm(forms.Form):
class Meta:
model = Stock
# incase you want all fields
fields = '__all__'
In views.py
from .forms import StockForm
from .models import Stock
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib import messages
def update_entry(request, pk):
try:
queryset = Stock.objects.get(id=pk)
except Stock.DoesNotExist:
messages.error(request, "The request entry does not exist.")
# Redirect back some page incase of invalid pk
return HttpResponseRedirect(reverse("app2:listing"))
# Populate the form with old data
form = StockForm(instance=qs)
context = {"form": form}
# When method is post
if request.method == "POST":
# Populate the form with newly posted data
form = StockForm(request.POST, instance=qs)
# Checking data validity in form
if form.is_valid():
form.save()
# Always use HttpResponseRedirect after successfull post request
return HttpResponseRedirect(reverse("some-url-name"))
# When form is not valid re-render page
else:
messages.error(request, "Invalid form received.")
# Update form in context dictionary
context["form"] = form
return render(request, "update-stock.html", context)
# When method is not post
else:
return render(request, "update-stock.html", context)
In update-stock.html
<div class="container-fluid">
<!-- Loop over messages rendered from views -->
{% for message in messages %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>{{ message }}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
<form method="post" action="" class="row g-1">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary">
</form>
</div>
I am getting a helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object error when trying to access a slice of the form. As shown in forms.py below, I would like to access the first Div using a layout slice (https://django-crispy-forms.readthedocs.io/en/latest/dynamic_layouts.html), so that I can display ONLY that Div within a tab in my HTML. In ref_detail.html below, I have tried to accomplish this with {% crispy form form_helper.0 %}. I've also tried {% crispy form form_helper[0] %} but that doesn't work either.
python version 3.8.3
django version 3.1.2
views.py:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse_lazy
from crispy_forms.utils import render_crispy_form
from .models import reference
from .forms import ReferenceForm
def ref_detail(request, ref_id):
try:
ref = reference.objects.get(pk=ref_id)
except ref.DoesNotExist:
raise Http404("Reference does not exist")
#If this is a POST request, process the form data
if request.method == 'POST':
#create a form instance and populate it with data from the request
form = ReferenceForm(request.POST)
#check whether it's valid
if form.is_valid():
#process the data in form.cleaned_data as required (i.e. save to database, etc.)
#...
print(form.cleaned_data)
new_reference = form.save() #save a new reference object to the database, from the form's data
#redirect to a new URL:
return HttpResponseRedirect('thanks/')
#if a GET (or any other method) we'll create a blank form
else:
form = ReferenceForm()
return render(request, 'test_cedar_app/ref_detail.html', {'ref': ref, 'form': form, 'form_helper': form.helper})
forms.py:
from django.forms import ModelForm
from django import forms
from test_cedar_app.models import factor, reference
from django.utils.translation import gettext_lazy as _
from crispy_forms.bootstrap import Tab, TabHolder, FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout_slice import LayoutSlice
from crispy_forms.layout import Submit, Layout, Div
from crispy_forms.utils import render_crispy_form
class ReferenceForm(ModelForm):
class Meta:
model = reference
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Div('study_title',
'name_author',
'publication_year',
'publisher',
'ident_doi',
'ident_pmid',
'exclude_extraction',
'exclude_extraction_reason',
css_id='main-tab-md',
css_class='tab-pane fade show active',
),
Div('study_design',
'study_design_detail',
'study_sample_method',
'ast_method',
'has_breakpoint',
'has_mic_table',
css_id='study-tab-md',
css_class='tab-pane fade',
),
)
ref_detail.html:
{% extends './base.html' %}
<!-- {% load static %} -->
{% load crispy_forms_tags %}
{% load widget_tweaks %}
{% block content %}
<form action="" method="post" id="leadform" enctype="multipart/form-data" role="form">
{% csrf_token %}
<ul class="nav nav-tabs md-tabs" id="myTabMD" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="main-tab-md" data-toggle="tab" href="#main-md" role="tab" aria-controls="main-md"
aria-selected="true">Main</a>
</li>
<li class="nav-item">
<a class="nav-link" id="study-tab-md" data-toggle="tab" href="#study-md" role="tab" aria-controls="study-md"
aria-selected="false">Study Design</a>
</li>
<li class="nav-item">
<a class="nav-link" id="location-tab-md" data-toggle="tab" href="#location-md" role="tab" aria-controls="location-md"
aria-selected="false">Location</a>
</li>
<li class="nav-item">
<a class="nav-link" id="history-tab-md" data-toggle="tab" href="#history-md" role="tab" aria-controls="history-md"
aria-selected="false">History</a>
</li>
<li class="nav-item">
<a class="nav-link" id="notes-tab-md" data-toggle="tab" href="#notes-md" role="tab" aria-controls="notes-md"
aria-selected="false">Notes and Issues</a>
</li>
</ul>
<div class="tab-content card pt-5" id="myTabContentMD">
<div class="tab-pane fade show active" id="main-md" role="tabpanel" aria-labelledby="main-tab-md">
{% crispy form form_helper.0 %}
</div>
<div class="tab-pane fade" id="study-md" role="tabpanel" aria-labelledby="study-tab-md">
<p>Study</p>
</div>
<div class="tab-pane fade" id="location-md" role="tabpanel" aria-labelledby="location-tab-md">
<p>Location</p>
</div>
<div class="tab-pane fade" id="history-md" role="tabpanel" aria-labelledby="history-tab-md">
<p>History</p>
</div>
<div class="tab-pane fade" id="notes-md" role="tabpanel" aria-labelledby="notes-tab-md">
<p>Notes</p>
</div>
</div>
</form>
{% endblock %}
base.html:
{% load static %}
<!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="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Update a Reference</title>
<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 type="text/javascript" src="{% static 'bootstrap-tab.js' %}"> </script>
<!-- MDB icon -->
<link rel="icon" href="{% static 'img/mdb-favicon.ico' %}" type="image/x-icon">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">
<!-- Google Fonts Roboto -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<!-- Material Design Bootstrap -->
<link rel="stylesheet" href="{% static 'css/mdb.min.css' %}">
<!-- Your custom styles (optional) - -->
</head>
<body>
<div class="container">
<div class="row justify-content-left">
<div class="col-8">
<h1 class="mt-2">{{ref.study_title}}</h1>
<hr class="mt-0 mb-4">
{% block content %}
{% endblock %}
</div>
</div>
</div>
<!-- SCRIPTS -->
<!-- jQuery -->
<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="{% static 'js/popper.min.js' %}"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="{% static 'js/mdb.min.js' %}"></script>
<!-- MDBootstrap Datatables -->
<!-- <script type="text/javascript" src="{% static 'js/addons/datatables.min.js' %}"></script> -->
<!-- Your custom scripts (optional) -->
</body>
</html>
You could remove the layout object in your view. The last few lines would look like:
form = ReferenceForm()
form.helper.layout.pop(1)
return render(request, 'test_cedar_app/ref_detail.html', {'ref': ref, 'form': form})
And then display your form as you usually do:
{% crispy form %}
I'm trying to build a system that allows users to upload images, I'm using Django 2.1 and I follow this course. I'm using the exact code but it doesn't work, I don't know what is the problem may be js code is not running This is my code
item_images_creation.html
{% load staticfiles %}
<!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">
<title>{% block title %}Photos Library - Simple is Better Than Complex{% endblock %}</title>
<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">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.page-header {
margin-top: 0;
}
</style>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
<script src="{% static 'photos/js/progress-bar-upload.js' %}"></script>
</head>
<body>
<div class="container">
<h1 class="page-header">
Photos
<small></small>
</h1>
<div class="row">
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Examples</h3>
</div>
<a href="{% url 'item:progress_bar_upload' %}" class="list-group-item{% if request.path == '/progress-bar-upload/' %} active{% endif %}">
Progress Bar Upload
</a>
</a>
</div>
</div>
</div>
<div class="col-md-9">
<div style="margin-bottom: 20px;">
<button type="button" class="btn btn-primary js-upload-photos">
<span class="glyphicon glyphicon-cloud-upload"></span> Upload photos
</button>
<input id="fileupload" type="file" name="file" multiple
style="display: none;"
data-url="{% url 'item:progress_bar_upload' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</div>
<table id="gallery" class="table table-bordered">
<thead>
<tr>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for photo in photos %}
<tr>
<td>{{ photo.file.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="modal fade" id="modal-progress" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading...</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
models.py
class Photo(models.Model):
title = models.CharField(max_length=255, blank=True)
file = models.FileField(upload_to='media/item_image')
uploaded_at = models.DateTimeField(auto_now_add=True)
forms.py
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('file', )
views.py
class ProgressBarUploadView(View):
def get(self, request):
photos_list = Photo.objects.all()
return render(self.request, 'zwwebsite/item_images_creation.html', {'photos': photos_list})
def post(self, request):
time.sleep(1) # You don't need this line. This is just to delay the process so you can see the progress bar testing locally.
form = PhotoForm(self.request.POST, self.request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
else:
data = {'is_valid': False}
return JsonResponse(data)
urls.py
from django.urls import path
from item.views import ProgressBarUploadView
app_name = 'item'
urlpatterns = [
path('progress-bar-upload/', ProgressBarUploadView.as_view(), name='progress_bar_upload'),
]
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
"""STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/static/',
]"""
# upload images
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
from django.contrib import admin
from django.urls import include, path
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from item.views import user_authentication
from . import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('authentication.urls')),
path('', include('stores.urls')),
path('', include('item.urls')),
path('', include('search.urls')),
path('check-login/', user_authentication, name='check-login'),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This is how my Network tab in browser looks like
Image link
there is noting appear in console tab
and that how my command line looks
Image link
Please help me solve this problem
i tried using class based views for signup but when i try to add images to the form fields, i keep getting this field is required the problem is with the image file
this is the forms.py file
`
from django import forms
from .models import User
class USerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['username', 'email', 'password', 'company', 'description', 'logo']
`
and the views.py file
from django.shortcuts import render, redirect
from django.views.generic import View, TemplateView
from .forms import USerForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic.edit import UpdateView
# Create your views here.
#login_required(login_url="/jembe/login/")
def index(request):
return render(request, 'base.html')
class SignUp(View):
form_class = USerForm
template_name = 'signup.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('invoice:index')
return render(request, self.template_name, {'form': form})
class LogoutView(View):
def get(self, request):
logout(request)
return HttpResponseRedirect('/jembe/login')
class AboutView(TemplateView):
template_name = "about.html"
models.py file
`from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
company = models.CharField(max_length=300)
description = models.TextField(blank=True)
website = models.URLField()
logo = models.ImageField(upload_to='../media/')
`
register.html
{% load staticfiles %}
{% load i18n widget_tweaks %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="img/favicon_1.ico">
<title>{% block title %} Signup {% endblock %} |Jims</title>
""
<!-- Bootstrap core CSS -->
<link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'login/css/bootstrap-reset.css' %}" rel="stylesheet">
<!--Animation css-->
<link href="{% static 'login/css/animate.css' %}" rel="stylesheet">
<!--Icon-fonts css-->
<link href="{% static 'login/assets/font-awesome/css/font-awesome.css' %}" rel="stylesheet" />
<link href="{% static 'login/assets/ionicon/css/ionicons.min.css' %}" rel="stylesheet" />
<!--Morris Chart CSS -->
<link rel="stylesheet" href="{% static 'login/assets/morris/morris.css">
<!-- Custom styles for this template -->
<link href="{% static 'login/css/style.css' %}" rel="stylesheet">
<link href="{% static 'login/css/helper.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
<link href="{% static 'css/main.css' %}" rel="stylesheet">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','../../../www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-62751496-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href=""><div class="logo">
<a href="" class="logo-expanded">
<i class="ion-compose"></i>
<span class="nav-label">Jigs</span>
</a>
</div></a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><strong>About</strong></li>
<li><strong>Login</strong></li>
<li><strong>Register</strong></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="wrapper-page animated fadeInDown">
<div class="panel panel-color panel-primary">
<div class="panel-heading">
<h3 class="text-center m-t-10"> Create a new Account </h3>
</div>
{# error logic #}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error | escape }}</strong>
</div>
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong> {{ error | escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
{# end error logic #}
<form class="form-horizontal m-t-40" action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<div class="col-xs-12">
<label> {{ field.label }} </label>
{{ field|attr:"class:form-control" }}
</div>
</div>
{% endfor %}
<div class="form-group ">
<div class="col-xs-12">
<label class="cr-styled">
<input type="checkbox" checked>
<i class="fa"></i>
I accept <strong>Terms and Conditions</strong>
</label>
</div>
</div>
<div class="form-group text-right">
<div class="col-xs-12">
<button class="btn btn-purple w-md" type="submit">Register</button>
</div>
</div>
<div class="form-group m-t-30">
<div class="col-sm-12 text-center">
Already have account?
</div>
</div>
</form>
</div>
</div>
<!-- js placed at the end of the document so the pages load faster -->
<script src="{% static 'login/js/jquery.js' %}"></script>
<script src="{% static 'login/js/bootstrap.min.js' %}"></script>
<script src="{% static 'login/js/pace.min.js' %}"></script>
<script src="{% static 'login/js/wow.min.js' %}"></script>
<script src="{% static 'login/js/jquery.nicescroll.js' %}" type="text/javascript"></script>
<!--common script for all pages-->
<script src="{% static 'login/js/jquery.app.js' %}"></script>
<hr/>
<center><h3 class="text text-success"> Jembe™ © 2017</h3></center>
</body>
</html>
You have forgotten to set enctype in your form. It should be:
<form class="form-horizontal m-t-40" action="" method="post" enctype="multipart/form-data">
See the Django docs on file uploads for more info.