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
Related
I am starting with Django 3 and python 3.8, and I have had a problem, I am trying to start the session and when I press the Ingresar button I get this error:
I have tried many things to try to solve it but I cannot, although I have found similar problems, the solutions they give have not worked for me.
This is the code I have so far:
principal urls.py
urlpatterns = [
path('',include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
path('index/', views.index)
]
app urls.py
urlpatterns = [
path('/index', views.index, name='index'),
path('/login', views.login, name='login'),
]
views.py
def index(request):
return render(request, 'index.html')
def login(request):
return render(request, 'login.html')
base_generic.html
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}<title>Read Praxis</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Add additional CSS in static file -->
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">
{% block sidebar %}
<ul class="sidebar-nav">
<li>Home</li>
<li>All books</li>
<li>All authors</li>
</ul>
{% endblock %}
</div>
<div class="col-sm-10 ">
{% block content %}{% endblock %}
</div>
</div>
</div>
</body>
</html>
login.html
<!doctype 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">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Jekyll v4.0.1">
<title>Login</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.5/examples/sign-in/">
<!-- Bootstrap core CSS -->
<link href="{% static 'assets/dist/css/bootstrap.css' %}" rel="stylesheet">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<link rel="stylesheet" href="{% static 'css/login.css' %}">
</head>
<body class="text-center">
<form class="form-signin" method="POST" action="">
{% csrf_token %}
<img class="mb-4" src="{% static 'images/rpp_logo.png' %}" alt="" width="150">
<h1 class="h3 mb-3 font-weight-normal">Por favor ingresa</h1>
<label for="inputUsername" class="sr-only">Usuario</label>
<input type="text" id="inputUsername" class="form-control" placeholder="Aquí tu usuario" required autofocus name="username">
<label for="inputPassword" class="sr-only">Contraseña</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Aquí tu contraseña" required name="password">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Recuérdame
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Ingresar</button>
<p class="mt-5 mb-3 text-muted">© Read Praxis Project</p>
</form>
</body>
</html>
index.html
{% extends "base_generic.html" %}
{% block content %}
<h1>Bienvenido {{ user.usermane | upper }}</h1>
{% endblock %}
settings.py
LOGIN_REDIRECT_URL = 'index'
The truth is that I don't know what else I could do, if someone has a solution I would really appreciate it
It is giving error because you have given same path for 'index/' at 2 places.
Remove it from app urls.py and replace it at principal urls.py like below.
principal urls.py
urlpatterns = [
path('index/', views.index, name='index'),
path('admin/', admin.site.urls),
path('',include('django.contrib.auth.urls')),
]
app urls.py
urlpatterns = [
path('/login', views.login, name='login'),
]
I am trying to load static files in a django project. I make a system of registration, login and password change. In the case when I go to the pages of my project, static files are loaded. However, if I reset my password and later go to the password change page (http://127.0.0.1:8000/password_reset_confirm/MQ-set-password/) django does not load static files.
I am using django 2.2.6, python 3.7.3.
Project structure
-project
-core
models.py
forms.py
views.py
...
-settings
settings.py
urls.py
...
-static
...
-templates
...
manage.py
...
urls.py
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth.views import PasswordResetView, PasswordResetCompleteView, PasswordResetConfirmView
from django.conf.urls import url
from core import views
urlpatterns = [
path('', views.home, name='home'),
path('signup/', views.signup, name='signup'),
path('login/', views.LoginView.as_view(), name="login"),
path('password_change_form/', views.LoginView.as_view(), name='password_change_form'),
path('password_change_confirm/', views.LoginView.as_view(), name='password_change_confirm'),
path('password_reset/', PasswordResetView.as_view(), name='password_reset'),
url(r'password_reset_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('password_reset_done/', PasswordResetCompleteView.as_view(), name='password_reset_done'),
path('secret/', views.secret_page, name='secret'),
path('admin/', admin.site.urls)
]
password_reset_confirm
{% extends 'base.html' %}
{% block content %}
<h2>Set new password</h2>
{% if validlink %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% else %}
<p style="color:red;">Invalid token.</p>
<p>
Request a new password reset token
</p>
{% endif %}
{% endblock %}
base.html
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<!-- Metas -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django Fishing</title>
<meta name="description" content="GRAPE – Multipurpose App Landing HTML Template is a modern, unique and clean design for your Business Purpose. Users will love Your site because it gives them a unique user experience.">
<!-- External CSS -->
<link rel="stylesheet" href="../static/core/assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../static/core/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="../static/core/assets/css/et-line.css">
<link rel="stylesheet" href="../static/core/assets/css/magnific-popup.css">
<link rel="stylesheet" href="../static/core/assets/css/animate.css">
<link rel="stylesheet" href="../static/core/assets/css/owl.carousel.css">
<link rel="stylesheet" href="../static/core/assets/css/owl.transitions.css">
<link rel="stylesheet" href="../static/core/assets/css/plyr.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="../static/core/css/style.css">
<link rel="stylesheet" href="../static/core/css/responsive.css">
<!-- Google font -->
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400%7CUbuntu:400,700%7COpen+Sans" rel="stylesheet">
<!-- Favicon -->
<link rel="icon" href="../static/core/images/favicon.png">
<link rel="apple-touch-icon" href="../static/core/images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../static/core/images/icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../static/core/images/icon-114x114.png">
<!--[if lt IE 9]>
<script src="../static/core/assets/js/html5shiv.min.js"></script>
<script src="../static/core/assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="loader-wrap" id="loader-wrap">
<div class="cssload-loader"></div>
</div>
<!-- Preloader End -->
<!-- Navigation -->
<nav class="navbar navbar-default" data-spy="affix" data-offset-top="60">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'home' %}">
<img src="../static/core/images/50h/logo.png" alt="Site Logo">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right" id="one-page-nav">
<li>Главная</li>
<li>Возможности</li>
<li>Почему мы</li>
<li>Форум</li>
<li>Цены</li>
<li>Поддержка</li>
<li>Скачать</li>
<li>Контакты</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<div id="banner" class="banner">
<div class="banner-item banner-1 steller-parallax" data-stellar-background-ratio="0.5">
</div>
</div>
{% block content %}{% endblock content %}
<footer>
<!-- Footer Subscribe -->
<div class="subscription-area section-padding theme-bg">
<div class="container">
<div class="row">
<div class="col-md-6">
<h3 class="wow fadeInLeft" data-wow-duration="1.5s">Подпишитесь на нашу<br/>новостную ленту</h3>
</div>
<div class="col-md-6">
<form class="subscription wow fadeInRight" data-wow-duration="1.5s" action="#" method="post">
<input type="email" name="email" placeholder="Введите вашу почту здесь" required>
<button type="submit">Подтвердить</button>
<p class="newsletter-success"></p>
<p class="newsletter-error"></p>
</form>
</div>
</div>
</div>
</div>
<!-- Footer Subscribe -->
<!-- Footer logo and social media button -->
<div class="logo-social-area section-padding">
<div class="container text-center">
<a class="logo logo-footer wow fadeInDown" data-wow-duration="1.5s" href="#">
<img src="../static/core/images/50h/logo.png" alt="Site Logo">
</a>
<div class="socials wow fadeInUp" data-wow-duration="1.5s">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<i class="fa fa-google-plus"></i>
<i class="fa fa-youtube-play"></i>
<i class="fa fa-vimeo"></i>
</div>
</div>
</div>
<!-- Footer logo and social media button -->
<!-- Footer copyrgiht and navigation -->
<div class="copyright-footer">
<div class="container">
<div class="row">
<div class="col-md-6 col-xs-12">
<p class="copyright"># Copyright 2019, django fishing. All Right Reserved</p>
</div>
<div class="col-md-6 col-xs-12">
<ul class="footer-nav">
<li>Правовая информация</li>
<li>Наша команда</li>
<li>Блог</li>
<li>FAQ</li>
</ul>
</div>
</div>
</div>
</div>
<!-- Footer copyrgiht and navigation -->
</footer>
<script src="../static/core/assets/js/jquery.min.js"></script>
<script src="../static/core/assets/js/bootstrap.min.js"></script>
<script src="../static/core/assets/js/jquery.nav.js"></script>
<script src="../static/core/assets/js/wow.min.js"></script>
<script src="../static/core/assets/js/jquery.localScroll.min.js"></script>
<script src="../static/core/assets/js/jquery.magnific-popup.min.js"></script>
<script src="../static/core/assets/js/owl.carousel.js"></script>
<script src="../static/core/assets/js/plyr.js"></script>
<script src="../static/core/assets/js/jquery.ajaxchimp.min.js"></script>
<script src="../static/core/assets/js/jquery.stellar.min.js"></script>
<script src="../static/core/js/map.js"></script>
<script src="../static/core/js/custom.js"></script>
</body>
</html>
Don't use explicit relative paths, use the {% static ...%} template tag. E.g. replace this:
<script src="../static/core/assets/js/jquery.min.js"></script>
with this:
<script src="{% static 'core/assets/js/jquery.min.js' %}"></script>
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>
I am working on a hotel booking site , in which i give the user a option to upload their hotel in the site, In that i am interested in user to upload multiple images with out any particular limit, i wrote the model , the user successfully uploading the images but i am unable to store it in the database .
I got struck on this issue, i have searched everything on the web from the past one week , still not yet resolved, please help me on this issue .
Here is my model
hotel_rating_choices = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
)
class Hotel(models.Model):
Hotel_Name = models.CharField(max_length=50)
location = models.CharField(max_length=20)
no_of_rooms = models.IntegerField()
rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3)
hotel_img = models.FileField(upload_to='hotel_images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
def __str__(self):
return self.Hotel_Name
Here is my form
class add_hotel(forms.ModelForm):
class Meta:
model = Hotel
fields = ('Hotel_Name', 'location', 'rating','no_of_rooms', 'user','hotel_img', )
# exclude = ['id']
widgets = {
'hotel_img' : forms.ClearableFileInput(attrs={'multiple': True})
}
Here is my view
class BasicUploadView(CreateView):
template_name = 'photos/basic_upload/index.html'
model = Hotel
form_class = add_hotel
success_url = reverse_lazy('home')
def get(self, request, *args, **kwargs):
form = add_hotel
return render(
self.request,
template_name = self.template_name,
context={'form' : form}
)
def post(self, request, *args, **kwargs):
import ipdb
ipdb.set_trace()
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
photo = form.save()
data = {'is_valid': True, 'name':photo.hotel_img.name, 'url': photo.hotel_img.url}
return redirect('home')
else:
data = {'is_valid' : False}
return render(request, self.template_name, {'form': form})
Here is my template
{% load static from staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Euphoria booking</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="{% static 'css/icomoon.css' %}">
<!-- Theme style -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
</head>
<body>
<div style="margin-bottom: 20px;">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<table id="gallery" class="table table-bordered">
<tbody>
{% csrf_token %}
{% for field in form %}
<tr>
{{ field.errors }}
<td> {{ field.label_tag }}</td>
<td>{{ field }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<b>For uploading of more hotel photos</b>
<div align="center">
<button type="button" class="btn btn-primary js-upload-photos">
Upload photos
</button>
<input id="fileupload" type="file" name="hotel_img" multiple
style="display: none;"
data-url="{% url 'basic_upload' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</div>
<input type="submit" value="Submit" style="margin-left: 37%;" />
</form>
</div>
<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>
{% block javascript %}
{# JQUERY FILE UPLOAD SCRIPTS #}
<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>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
{# PHOTOS PAGE SCRIPTS #}
<script src="{% static '/js/progress-bar-upload.js' %}"></script>
{% endblock %}
</div>
</body>
</html>
Ignore the progress bar , css stuff, i want to know why i am unable to store multiple images
Reference
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.