I'm New in Django 2. I was trying to upload a file in Django here is my code
View.py
def addBook(request):
checkName = AddBook.objects.filter(title=request.POST.get('title'))
if not checkName:
bookAdd = AddBook(
title=request.POST.get('title'),
slug=slugify(request.POST.get('title')),
description=request.POST.get('description'),
cover_image=request.FILES.get('cover_image'),
file=request.FILES.get('file'),
category=request.POST.get('category'),
created_by=request.user.id,
)
bookAdd.save()
messages.add_message(request, messages.INFO, 'Book Saved Successfully')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
messages.add_message(request, messages.INFO, 'Book Title Already Exists')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Update As per Comment
Here is my template code
bookSave.html
<form action="{% url 'addBook' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs 12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-edit"></i>
</div>
<div class="nk-int-st">
<input type="text" class="form-control input-sm" required="required" name="title"
Placeholder="Title">
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-mail"></i>
</div>
<div class="nk-int-st">
<textarea class="form-control input-sm" required="required" name="description"
placeholder="Description"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-dollar"></i>
</div>
<div class="nk-int-st">
<input type="file" name="cover_image" required="required" class="form-control input-sm">
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-house"></i>
</div>
<div class="nk-int-st">
<input type="file" name="file" required="required" class="form-control input-sm">
</div>
</div>
</div>
</div>
<div class="modal-body">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group ic-cmp-int">
<div class="form-ic-cmp">
<i class="notika-icon notika-next"></i>
</div>
<div class="nk-int-st">
<input type="text" name="category" required="required" class="form-control input-sm"
Placeholder="Category">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
I can save everything but I need to save the file path and save the file locally. I read their documentation but cannot help me out. Please help me to solve this problem
The FileField in your Model, besides the other fields, should look like this:
class AddBook(models.Model):
# file will be uploaded to MEDIA_ROOT/uploads
file = models.FileField(upload_to='uploads/')
# or...
# file will be saved to MEDIA_ROOT/uploads/2015/01/30
file = models.FileField(upload_to='uploads/%Y/%m/%d/')
In your settings file, you’ll need to define MEDIA_ROOT as the full path to a directory where you’d like Django to store uploaded files. (For performance, these files are not stored in the database.) Define MEDIA_URL as the base public URL of that directory. Make sure that this directory is writable by the Web server’s user account.
in settings.py you should set for example:
MEDIA_ROOT = '/home/foo/bar/yourproject/assets'
Also you might want to study and set static files storage in Django (besides the ‘static’ folder).
https://docs.djangoproject.com/en/2.0/howto/static-files/#configuring-static-files
In Django you can get any file with the File Object like:
from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/mybookfile.pdf')
myfile = File(f)
Related
I'd like to get data from one form that has multiple textareas inside , In my views: 'compare_ingredients' I've tried requesting data from my form id 'compareform' also the textarea id 'ingredients', but when I enter something into one texture and click on submit it comes back as 'None' when I print. Here is my html and views:
html :
<div class="container-fluid">
<h4>Please enter in your ingredients:</h4>
<h6>(Seperate each item by comma)</h6>
<br>
<button class="add_item">Add Item</button>
<br>
<div class="row row-cols-1 row-cols-md-2 mx-auto">
<form action="{% url 'compare_ingredients' %}" method="POST" name="compareform" id="compare">
{% csrf_token %}
<br>
<button type="submit" class="btn btn-info sub_btn">Submit</button>
<button type="submit" class="btn btn-secondary back_button">
Back
</button>
<br>
<br>
<div class="row form_row">
<div class="col mb-4">
<h5>Item 1</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients1" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
<div class="col mb-4">
<h5>Item 2</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
views.py:
def compare_ingredients(request):
if request.method == "POST":
ingredients = request.POST.get('compareform')
print(ingredients)
return render(request, 'result/compare.html')
ok, I figured it out , the problem was in the html textarea I had the name of the form as 'compareform' when it should have been 'compare' :
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compare"></textarea>
then in my views I did:
ingredients1 = request.POST.get('ingredients1')
'''
My problem is database values can't stored properly
In below I uploded views functions file,model file as an images. so in model there are three fields but database stored only image stored and other vlaues strored by default get null values so can you help to solving my problem..
'''
userproblem.html
<form method="POST" action="/uploadoc/" enctype="multipart/form-data" data-toggle="validator">
{% csrf_token %}
<div id="progressbarwizard">
<ul class="nav nav-pills bg-light nav-justified form-wizard-header mb-3">
<li class="nav-item">
<a href="#account-2" data-toggle="tab" class="nav-link rounded-0 pt-2 pb-2">
<i class="mdi mdi-account-circle mr-1"></i>
<span class="d-none d-sm-inline">Query Form</span>
</a>
</li>
</ul>
<div class="tab-content b-0 mb-0">
<div class="tab-pane" id="account-2">
<div class="row">
<div class="col-md-5">
<label class="col-md-12 col-form-label">Query Types:
<span class="text-danger">*</span></label>
<div class="col-md-8">
<input type="text" class="form-control" data-validate="true" name="queryn" placeholder="Enter Query Types">
</div>
</div>
<div class="col-md-5">
<label class="col-md-12 col-form-label">Description of Query:
<span class="text-danger">*</span></label>
<div class="col-md-12">
<textarea type="text" class="form-control" data-validate="true" name="querydec" placeholder="Description of Query"></textarea>
</div>
</div>
</div><!-- /.First row end --><br>
<div class="row">
<div class="col-md-5">
<label for="Emailadrress" class="col-md-12 col-form-label">Upload Your File:
<span class="text-danger"></span></label>
<div class="col-md-12">
<div class="input-group-append">
<input type="file" id="img" name="img" accept="image/*">
</div>
</div>
</div>
<div class="col-md-6">
<label for="Emailadrress" class="col-md-12 col-form-label">Solutions:
<span class="text-danger"></span></label>
<div class="col-md-12">
<div class="input-group-append">
<textarea type="text" name="querysol" placeholder="Solutions of Query"></textarea>
</div>
</div>
</div>
</div> <!-- /.second row end -->
</div><br>
<div class="row">
<div class="col-12">
<div class="text-center">
<div class="mb-3">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck3">
<button type="submit" class="btn btn-primary">
<i class="icon-user icon-white"></i> Submit
</button>
</div>
</div>
</div>
</div> <!-- end col -->
</div>
</div> </div>
</form>
'[This is error and views function file my model imagespage][1]
You are trying to set c variable from userProblemModel named POSTed data in your uploadoc view.
c = request.POST.get('userProblemModel')
But in your form in html side there is no userProblemModel named input tag. That is why you are getting None value in c variable.
I am using the following UpdateView in order to alter some values in the database:
class MyUpdateView(UpdateView):
model = MyModel
fields = ['VideoURL', 'MainDescription']
template_name = 'myapp/edit.html'
This is my template:
<div class="row">
<div class="col-12 col-lg-7">
<form method='post' class="card shadow-soft border p-4 mb-4">
{% csrf_token %}
<h5 class="mb-4">General</h5>
<div class="form-group">
<label for="MainDescription">Title</label>
{{form.MainDescription|add_class:"form-control shadow-soft"}}
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2"
type="submit">Update</button>
</div>
</div>
</form>
</div>
<div class="col-12 col-lg-5">
<form method='post' class="card shadow-soft border p-4 mb-4">
{% csrf_token %}
<div class="form-group">
<label for="VideoURL">Video URL:</label>
{{form.VideoURL|add_class:"form-control shadow-soft"}}
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
</div>
</div>
However, I am facing some difficulties doing so because although both fields belongs to the same model, I cannot update any of the information. What I have noticed though is that if I place the both fields under the same HTML form, it works:
<div class="col-12 col-lg-5">
<form method='post' class="card shadow-soft border p-4 mb-4">
{% csrf_token %}
<div class="form-group">
<label for="VideoURL">Video URL:</label>
{{form.VideoURL|add_class:"form-control shadow-soft"}}
</div>
<div class="form-group">
<label for="MainDescription">Main Description:</label>
{{form.MainDescription|add_class:"form-control shadow-soft"}}
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
</div>
What am I missing here? Can anyone give me a hint? Thanks
Edit
It's due to how the forms are being displayed in the HTML form. They should be independent:
I am using js plugin to upload image, first time when i select image from the plugin the form gets submitted. The issue is that i select the image first time but then i don't want that image and i click on it again to upload another image, the form does not get validated and fails to submit.
views.py
class SelectObituaryView(LoginRequiredMixin, TemplateView):
template_name = "website/obituary_select.html"
def get_context_data(self, **kwargs):
context = super(SelectObituaryView, self).get_context_data(**kwargs)
church_id = self.request.session.get('church_id', None)
if church_id:
samples = ObituarySample.objects.filter(organization__id=church_id)
context['obituary_samples'] = samples
context['church_cover'] = self.request.session.get('church_cover', None)
return context
#transaction.atomic
def post(self, request):
print("Entered function")
try:
data = request.POST.copy()
data['organization'] = request.session.get('church_id', None)
data['slug'] = data['name'].replace(' ', '-')
data['funeral_time'] = data['funeral_time'].replace(" ", "")
data['viewing_time'] = data['viewing_time'].replace(" ", "")
if len(request.FILES.getlist('gallery')) > 10:
messages.error(request, "Max gallery images limit exceeded.")
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
obituary_form = ObituaryForm(data=data, files=request.FILES)
# print("obituary form data",data)
print("before is valid")
if obituary_form.is_valid():
print("Inside is_valid")
obituary_instance = obituary_form.save(commit=False)
obituary_instance.image = obituary_instance.obituary_sample.background
obituary_instance.user = request.user
obituary_instance.save()
obituary_instance.update_slug_with_id()
#override profile_image
#imageName = os.path.basename(obituary_instance.profile_image.path)
imgArr = os.path.split(obituary_instance.profile_image.path)
image_data = request.POST['profile_image1']
b = json.loads(image_data)
head, data = b["output"]["image"].split(',')
binary_data = a2b_base64(data)
print(binary_data)
with open(obituary_instance.profile_image.path, 'wb+') as fh:
myfile = File(fh)
myfile.write(binary_data)
imprinted_image_path = apps.obituary.utils.imprint(obituary_instance, obituary_instance.obituary_sample)
# Save imprinted image in db
with open(imprinted_image_path, 'rb') as f:
data = f.read()
file_postfix = datetime.now().strftime("%Y%m%d-%H%M%S")
obituary_instance.image.save("%s%s.jpg" % ('obituary', file_postfix), ContentFile(data))
for gallery_image in request.FILES.getlist('gallery'):
GalleryImage.objects.create(obituary=obituary_instance, image=gallery_image)
return HttpResponseRedirect(reverse('obituary:preview', kwargs={'obituary_id': obituary_instance.id}))
else:
print("else")
messages.error(request, constants.OPERATION_UNSUCCESSFUL)
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
except Exception as e:
print(e)
print("except")
messages.error(request, "Unable to create, Please try again.")
return HttpResponseRedirect(
reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')}))
html
{% extends "website/base.html" %}
{% load static %}
{% block javascript %}
<script>
// Submit post on submit
{# $('#create_obit').on('submit', function(event){#}
{# event.preventDefault();#}
{# alert("Aamixsh");#}
{# });#}
$("#create_obit").submit(function(evt){
//evt.preventDefault();
if($(this).find('input[name="profile_image"]').val() != "") {
$(this).find('input[name="profile_image"]').attr('name','profile_image1');
$(this).find(".slim").find('input[type="file"]').attr('name','profile_image');
return true;
}
});
$(document).ready(function(){
$('input[type="text"]').attr( 'autocomplete', 'off' );
$('.dateReadonly').attr( 'readonly', 'true' );
});
</script>
{% endblock %}
{% block body_block %}
<!-- Banner Area Start -->
<div class="banner-area">
<div class="overlay"></div>
<div class="img-holder">
<div class="holder"><img src="{{ church_cover }}" alt=""></div>
</div>
<div class="caption">
<div class="holder">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="banner">
<h2>Fill in Loved Ones Details</h2>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="section-space">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="row">
<h3 class="heading-title">Create an Obituary</h3>
<form class="setting-form" id="create_obit" action="{% url 'obituary:select' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
<div class="col-xs-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Name: <input type="text" maxlength="50" name="name" placeholder="Name*" class="form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Funeral Address: <input type="text" maxlength="50" name="address" placeholder="Funeral Address*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Date of Birth: <input type="text" id="datepicker1" name="date_of_birth" placeholder="Date of Birth*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Date of Death: <input type="text" id="datepicker2" name="date_of_death" placeholder="Date of Death*" class="dateReadonly form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Funeral Date: <input type="text" name="funeral_date" id="datepicker3" placeholder="Funeral Date*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Funeral Time: <input type="text" name="funeral_time" id="timepicker" placeholder="Funeral Time*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Surviving Family: <input type="text" maxlength="100" name="family_info" placeholder="spouse Mary Louise, and sons Joe, Ed, and Tim, etc. (Max Limit: 100 Characters)" class="form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Ways To Contribute: <input type="text" maxlength="40" name="memorial_donation_info" placeholder="e.g. Donation url or other Information* (Max Limit: 40 Characters)" class="form-control input-field" >
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Viewing Date: <input type="text" name="viewing_date" id="datepicker4" placeholder="Viewing Date*" class="dateReadonly form-control input-field" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
Viewing Time: <input type="text" name="viewing_time" id="timepicker2" placeholder="Viewing Time*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
Viewing Address: <input type="text" maxlength="50" name="viewing_address" placeholder="Viewing Address*" class="form-control input-field" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
Message: <textarea maxlength="500" name="message" id="" cols="30" rows="10" class="form-control input-field" placeholder="Message* (Max Limit: 500 Characters)" required></textarea>
</div>
</div>
</div>
<input type="hidden" name="obituary_sample" value="{{ obituary_form.obituary_sample.value }}" />
</div>
<div class="col-sm-12">
<h3>Upload Obituary Photo</h3>
<div class = "form-group">
Maximum image size is 8 MB. You can rotate and crop the uploaded image by using the control buttons at the bottom of the image.
<!-- original <input type="file" name="profile_image" placeholder="Obituary Image*" class="form-control input-field" required> -->
<input type="file" name="profile_image" placeholder="Obituary Image*" class="slim" required>
</div>
</div>
<div class="col-xs-12">
<h3>Upload Gallery Photos</h3>
<div class="dropzone" id="my-awesome-dropzone">
<div class="fallback">
(Maximum image size should be 8 MB)
<input type="file" name="gallery" multiple class="form-control input-field"/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="checkbox" onchange="document.getElementById('create').disabled = !this.checked;" /> I understand, that the obituary cannot be edited once paid for!
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<button type="submit" id="create" class="btn send-btn" disabled>Create</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
My Flask app already serves up several pages. I just made channels.html. For a route, I copied down and changed /messages, which already works. I then tried adding a link from messages.html to channels.html, but received the error: Could not build url for endpoint 'channels'. Did you mean 'index' instead? The error references the line Channels in messages.html. I checked spelling, syntax, decorator placement, and duplicative names; everything looks ok. Plus, the new code was built off of code that was previously tested.
So, why the error?
#app.route('/channels', methods=["GET", "POST"])
def channels():
return render_template("channels.html")
#app.route('/messages', methods=["GET", "POST"])
def messages():
return render_template("messages.html")
messages.html (top part)
{% extends "layout.html" %}
{% block body %}
<div class="container">
<div class="row" style="min-height: 100vh">
<div class="col-md-3 border border-danger rounded">
<div class="row mt-2 justify-content-start">
Header
</div>
<!-- <div class="row mt-2 justify-content-start" id="channelHeader">
Channels
</div>-->
<div class="row mt-2 justify-content-start" id="channels">
Channels
</div>
<div class="row justify-content-start" id="dmsg">
Direct Messages
</div>
</div>
<div class="col-md-9 border border-danger rounded">
{% endblock %}
channels.html
{% extends "layout.html" %}
{% block body %}
<div class="container">
<div class="display-3">
<strong>Create A Channel</strong>
</div>
<form action="{{ url_for('channels') }}" id="channelForm" class="mt-4">
<!-- Will need check for duplicate email -->
<div class="form-group">
<label for="channelName">Channel Name</label>
<input type="text" class="form-control" id="channelName" aria-describedby="channelName" placeholder="Enter Channel Name">
</div>
<!-- Will need check for duplicate username -->
<div class="form-group">
<label for="inviteUsers">Invite Other Users (optional)</label>
<input type="text" class="form-control" id="inviteUsers" aria-describedby="inviteUsers" placeholder="Search by name">
</div>
<div class="form-group">
<label for="purpose">Purpose</label>
<textarea type="text" class="form-control" id="purpose" rows="3" placeholder="Purpose">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}