Getting Image from image field to views.py model - python

I am making a social media site in Django. I have a page for making a new post. It has a form with a file field to take an image upload. I want to get the image in views.py to save in the database. In the image variable, a string is getting saved with the name of the image. Also, I don't want to use any external form like forms.py. Here I have also tried request.FILES["image"] but it returned an empty dict.
Views.py
def newpost(request):
if request.method == "POST":
image = request.POST.get("image")
caption = request.POST.get("caption")
post = Post(Image=image,Caption=caption,Owner=request.user.username)
post.save()
return redirect("/")
return render(request,"newpost.html")
newpost.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spark X- New Post</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/newpost.css' %}">
<script class="jsbin" src="{% static 'js/jquery.js' %}"></script>
<link rel="icon" href="{% static 'images/favicon123.png'%}" type="image" sizes="16x16" class="favicon">
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</head>
<body>
<div class="header">
<span class="topband">
<img src="{% static 'images/back icon.png'%}" class="topicon">
</span>
<div class="logoholder">
<p class="logotext">New Post</p>
</div>
</div>
<div class="mainarea">
<form action="" method="post">{% csrf_token %}
<input type="file" name="image" id="image" accept="image/*" class="imageUpload" onchange="readURL(this);"/>
<label for="image"><img src="{% static 'images/camera icon.png' %}" class="cameraIcon" id="blah"></label>
<input type="text" name="caption" placeholder="Caption... " class="caption">
<button type="submit" class="submit">Post</button>
</form>
</div>
</body>
</html>
models.py
class Post(models.Model):
Id = models.AutoField(primary_key=True)
Image = models.ImageField(upload_to="Posts")
date = models.DateTimeField(auto_now=True)
Caption = models.TextField()
Your help will really be appreciated.

I have figured it out. Just used request.FILES["image"] and added enctype="multipart/form-data" in form and it worked.

Related

Django How to make form fit HTML input field

I have a small question.
Here is my "Register page":
[![Register page][1]][1]
But when I add my form to the login, for example, I get this:
[![Page with login][2]][2]
I want to know how can I make that form box fit that HTML input field?
I don't know if I have to resize it in the forms.py or if there was a way for it to always bind up the input size that is in the HTML file.
This is the HTML:
{% load static %}
<!DOCTYPE html>
{% csrf_token %}
<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.0" />
<title>IPV QS Tool Registration</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="registration.css" />
<link rel="stylesheet" type="text/css" href="{% static 'css/style_register.css' %}" />
</head>
<body>
<form method="POST" action="">
<label>
<p class="label-txt">ENTER YOUR AMAZON EMAIL</p>
<input type="email" class="input" required />
<div class="line-box"></div>
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">ENTER YOUR AMAZON LOGIN</p>
{{form.username}}
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">CREATE A PASSWORD</p>
<input
type="password"
class="input password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required
/>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<button type="submit">Submit</button>
</form>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"
></script>
<script src="registration.js"></script>
</body>
</html>
Forms.py:
class createUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
It seems like you are missing class="input" from your input field. Please try this,
username = forms.CharField(max_length=100,
widget= forms.TextInput
(attrs={'class':'input'}))
widget= forms.TextInput(attrs={'class':'input'})
It will result in addition of this class to your CharField.
I hope this helps. Feel free to connect in case if the issue still persists.
Thanks.

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)

How to add a datepicker into Django ModelFrom?

These are my scripts -
models.py
from django.db import models
class Leave(models.Model):
...
from_date = models.DateField()
to_date = models.DateField()
def __str__(self):
return self.name
I wanted to have datepickers for the above DateField(s).
This is my form template:-
{% extends "base.html" %}
{% block content %}
<div class="container">
<h3> Fill out the form please! </h3>
<h4>
<form action="." role="form", method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type = "submit">Submit</button>
</form>
</h4>
</div>
{% endblock %}
So far, what i have done -
I have included this in my base.html.
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>
In my forms.py as I'm using ModelForms, I have included this code -
class LeaveRequestForm(ModelForm):
class Meta:
fields = ("from_date", "to_date")
model = Leave
widgets = {
'from_date' : DateInput(attrs={'class': 'datepicker'}),
'to_date' : DateInput(attrs={'class': 'datepicker'}),
}
But no datepicker is being reflected in my html template. I have read many other question related to this but couldn't understand. Hope, anyone explains me in detail.
base.html
...
<html>
<head>
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
...
</head>
I think your code is correct. However, from your comment it looks like you're using Bootstrap. You need to import Jquery BEFORE bootstrap.min.js and not after. If you have a javascript error in your page, it will prevent the datepicker from working.

Unable to store multiple images in django database

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

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