Django Upload Image can not find uploaded image - python

I am new to Django and deploying upload image function recently.
I developed simple HTML template and it worked, but somehow, I could not find the uploaded images.
Below are my code.
settings.py (relevant lines)
MEDIA_ROOT = '/Users/jenny/Envs/django_test/static/'
MEDIA_URL = '/media/'
models.py
from django.db import models
from time import time
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" % (str(time()).replace('.','_'), filename)
# Create your models here.
class UploadImage(models.Model):
thumbnail = models.FileField(upload_to=get_upload_file_name)
def __unicode__(self):
return self.thumbnail
forms.py
from django import forms
from .models import UploadImage
class UploadImageForm(forms.ModelForm):
class Meta:
model = UploadImage
fields = ('thumbnail',)
views.py
def uploadtest(request):
return render_to_response("uploadtest.html",context_instance=RequestContext(request))
def uploadtest1(request):
if request.POST:
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/uploadtest1/',context_instance=RequestContext(request))
else:
form = UploadImageForm()
return render_to_response ('uploadtest1.html',context_instance=RequestContext(request))
uploadtest.html
<form action="{% url "uploadtest1" %}" method="post" enctype="multipart/form-data">{% csrf_token %}
<p>
<input id="id_image" type="file" class="" name="image">
</p>
<input type="submit" value="Submit" />
</form>
uploadtest1.html
<p> uploaded! </p>
Would you please help me point out the problem? And how do I change the code to make it work?

I think you have misspelled your html input. In your model the field is named thumbnail, but the name of your input is image.
Make your input read like:
<input id="id_thumbnail" type="file" class="" name="thumbnail">

I solved the problem and now the code is running well on my launched website.
forms.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
models.py
from django.db import models
# Create your models here.
class Document(models.Model):
#docfile = models.FileField(upload_to='documents/%Y/%m/%d')
docfile = models.FileField(upload_to='documents/')
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from uploadfile.models import Document
from uploadfile.forms import DocumentForm
def imageupload(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('uploadfile.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
doc_list = []
documents = Document.objects.all()
for document in documents:
doc_list.append(document.docfile.name)
print doc_list[-1]
# Render list page with the documents and the form
return render_to_response('imageupload.html',
{'documents': documents,'form': form},
context_instance=RequestContext(request))
def imageuploadresult(request):
#here I used PyImgur package to upload image and get public url. Use sbi to get the Google BestGuess. What I return to this page is the uploaded image and google best guess. I will skip this part of code.
return render_to_response(
'imageuploadresult.html',
{'query': q, 'imagepath':path2},
context_instance=RequestContext(request))
imageupload.html
<!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title> Image Upload of **** System</title>
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static/css/dashboard.css" rel="stylesheet">
<!-- Custome CSS -->
<link href="/static/css/dataurl2.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="/static/js/ie8-responsive-file-warning.js"> </script><![endif]-->
<script src="/static/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<!--script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script-->
<!--script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"> </script-->
<script src="/static/js/html5shiv.min.js"></script>
<script src="/static/js/respond.min.js"></script>
<!--script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
})
</script-->
<![endif]-->
</head>
<body>
<!--div class="loader"></div-->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data- toggle="collapse" data-target="#navbar" aria-expanded="false" aria- controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href='/navigation/'>AKEOS</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>Dashboard</li>
<li>Settings</li>
<li>Profile</li>
<li>Help</li>
</ul>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li>Reports</li>
<li>Export</li-->
</ul>
<ul class="nav nav-sidebar">
<li class="active">(current)</span></li>
<li>Analytics</li>
<li>Export</li-->
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main list-group">
<h1></h1>
<h2></h2>
<h3 class="custome-bar">
<h1></h1>
<h2></h2>
<form action="{% url "imageuploadresult" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" style="font- size:10pt;color:white;background-color:#339933;border:2px solid #339933;padding:3px" /></p>
</form>
</h3>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/docs.min.js"></script>
<script src="/static/js/pace.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
imageuploadresult.html
<!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title> Image Upload of **** System</title>
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static/css/dashboard.css" rel="stylesheet">
<!-- Custome CSS -->
<link href="/static/css/dataurl2.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="/static/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="/static/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<!--script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script-->
<!--script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script-->
<script src="/static/js/html5shiv.min.js"></script>
<script src="/static/js/respond.min.js"></script>
<!--script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
})
</script-->
<![endif]-->
</head>
<body>
<!--div class="loader"></div-->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href='/navigation/'>AKEOS</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<!--li>You searched for:<strong> {{query}} </strong></li-->
<li>Dashboard</li>
<li>Settings</li>
<li>Profile</li>
<li>Help</li>
</ul>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
</ul>
<ul class="nav nav-sidebar">
<!--li>Analytics</li>
<li>Reports</li>
<li>Export</li-->
</ul>
<ul class="nav nav-sidebar">
<li class="active">(current)</span></li>
<!--li>Reports</li>
<li>Analytics</li>
<li>Export</li-->
</ul>
</div>
<!--div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"-->
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main list-group">
<h3 class="custome-bar">
<h3>The Best Guess is:<strong> {{query}} </strong>
<form action="/main-page/" method="get">
<h5> To start over again, click the sidebars; to continue, click the button "Search" </h5>
<h5>
<input type="submit" name = "Submit" value="Search" >
</h5>
<h3></h3>
</form>
</h3>
<!--a class="btn btn-large btn-info" href="/main-page/">Search</a-->
<p><img src={{imagepath}} class='img-responsive' /></p>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/docs.min.js"></script>
<script src="/static/js/pace.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
create table in MySQL
table name : upload file_document
table columns : ID, docfile
Now you can get it work on your website!
Have a nice day!

Related

Calling function from other app into main app

I am trying to get navigation bar to work across all apps. But i am not able to call the function from there.
this is my base.html.
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- Main CSS file -->
{% load static %}
<link rel="stylesheet" href="{% static 'main/main.css' %}">
{% block style %} {% endblock %}
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Chili Pili</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item btn-login">
Login
</li>
</ul>
</div>
</nav>
<div class="main">
{% block content %}
{% endblock %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" 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.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
I am trying to call the login function which goes to the login page in login app on main page url. Also I want to make the login function works across different apps. Therefore, I am not able to call the function here (in the example code provided). Is there any way I can call the login function here (in the example code provided). So, I don't have to create login page again.
If your base.html say is in an app called pages, and the template path is pages/templates/pages/base.html you can do in all apps
{% extends 'pages/base.html' %}

Static files on password_reset_confirm in django project page do not load

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>

How do I reset my HTML form with Python Flask?

I'm building a very simple web app (using Python Flask) that will display some images to the user and get some response from the user.
Below is my code (ignoring the other parts of my code not related to this question):
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Gallery</h1>
</div>
{{image_names}}
<hr>
<form method="POST">
{% for image_name in image_names %}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<img class="img-responsive" src=" {{url_for('send_image', filename=image_name)}}">
<input type="radio" name={{image_name}} id="radio1" value="YES" />YES<br>
<input type="radio" name={{image_name}} id="radio2" value="NO"/>NO<br>
<hr>
</div>
{% endfor %}
<input type="submit" name="submit_button" value="SUBMIT"/>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
</body>
</html>
My current app
Question:
I want to reset the form as soon as the user hits submit and capture the output in list "B". The form should not be resubmitted with old values if the user hits refresh.
Do a request method check and put in your capture login in it.
from flask import request
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
if request.method == "POST":
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)

login_required decorator in Django doesn't work

I'm working on a Django(1.10) project in which I need to load a template only for logged in users, which is coming from profile template.I need to load generateCert.html only for logged in user, this template should display the same navbar as profile template because both of these templates have the same header.
Here's my generateCert.html template:
{% load staticfiles %}
{% load static from staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NAMI Montana | User's Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content=""/>
<meta name="author" content="http://webthemez.com"/>
<!-- css -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"/>
<link href="{% static 'css/fancybox/jquery.fancybox.css' %}" rel="stylesheet">
<link href="{% static 'css/flexslider.css' %}" rel="stylesheet"/>
<link href="{% static 'css/style.css' %}" rel="stylesheet"/>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<!--Pulling Awesome Font -->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]><![endif]-->
<style>
input[type="image"] {
padding-left: 30%;
padding-top: 5%;
font-size: 1em;
color: #fff;
background: transparent;
border: 1px solid #fff;
font-weight: bold;
width: 70%;
}
</style>
</head>
<body>
<div class="topbar">
<div class="container">
<div class="row">
<div class="col-md-12">
<p class="pull-left hidden-xs"><i class="fa fa-envelope"></i><span>matt#namimt.org </span></p>
<p class="pull-right"><i class="fa fa-phone"></i>Tel No. (406) 443-7871</p>
</div>
</div>
</div>
</div>
<!-- start header -->
<header>
<div class="navbar navbar-default navbar-static-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="{% url 'home' %}"><img src="{% static 'images/logo.png' %}" alt="logo"
width="190px" height="50px;"/></a>
</div>
<div class="navbar-collapse collapse ">
<ul class="nav navbar-nav">
{% if not user.is_authenticated %}
<li>Home</li>
<li>About</li>
<li>Blog</li>
<li>Login</li>
<li>SignUp</li>
<li>Contact</li>
{% endif %}
{% if user.is_authenticated %}
<li>Home</li>
<li>Dashboard</li>
<li class="active">Profile</li>
<li>Logout</li>
<li>Contact</li>
{% endif %}
</ul>
</div>
</div>
</div>
</header>
<!-- end header -->
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8" style="margin-top: 5%">
<div class="panel panel-default">
<div class="panel-heading">
<h4> You have to pay <b> $95 </b> to generate your certificate.</h4>
</div>
{% block content %}
{{ form.render }}
{% endblock %}
</div>
</div>
</div>
</div>
{% include 'footer.html' %}
Here are my views.py:
#login_required
def payment_process(request):
if request.user.is_authenticated():
minutes = int(request.user.tagging.count()) * 5
testhours = minutes / 60
hours = str(round(testhours, 3))
# pdb.set_trace()
# What you want the button to do.
invoice = generate_cid()
paypal_dict = {
"business": settings.PAYPAL_RECEIVER_EMAIL,
"item_name": "Certificate of Completion from Nami Montana",
"custom": {"name": str(request.user.first_name + ' ' + request.user.last_name),
"hours": str(hours)},
"invoice": str(invoice),
"amount": "5.00",
"notify_url": "https://8bf57d43.ngrok.io/users/paypal/",
# "return_url": "https://b906ef46.ngrok.io/users/profile/",
"cancel_return": "https://8bf57d43.ngrok.io/users/cancel/",
}
print(paypal_dict)
# Create the instance.
form = PayPalPaymentsForm(initial=paypal_dict)
context = {"form": form}
return render_to_response("users/generateCert.html", context)
else:
return HttpResponseRedirect('/users/login')
Here is my urls.py:
url('^process/$', views.payment_process, name='payment'),
generateCert.html template display the menu of Anonymous users not logged in users menu, that means this template loaded by the unauthenticated user. How can I strict this template to only logged in users as it's coming from the profile page.
No, it doesn't mean that at all. What it does mean is that you are not passing the user to the template. This is because you are using render_to_response - which apart from anything else is deprecated - rather than the render shortcut which runs context processors.
Note, your login_required decorator makes that if request.user.is_authenticated() check pointless; the user will never not be authenticated.
Also note that you really should be using template inheritance to break out things like the top nav and the HTML boilerplate into their own templates.

Sign up django with cbv and AbstractUser model image error

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.

Categories