Passing Parameters From a Class Based View in Django - python

I have a class based Update view "ManifestUpdate", which is a modal pop up, and is launched from within another function based view "Manifest". I need to be able to take the field = 'reference' from my ManifestUpdate view and make it available to the "Manifest" view as 'Reference_Nos'. As you can see ManifestUpdate should direct the user to Manifest, but it does not, just nothing happens (it works if I change this to direct to any other view). I believe this is because I am not passing that parameter. Can anyone tell me how to capture that 'reference' parameter within ManifestUpdate and pass it to Manifest from the class based view?
views.py
class ManifestUpdate(BSModalUpdateView):
model = Manifests
template_name = 'manifest_update.html'
form_class = UpdateManifestForm
success_message = 'Success: Manifest was updated.'
success_url = reverse_lazy('manifest')
def manifest(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
reference_id = form.cleaned_data.get('reference')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
else:
reference_id = request.POST.get('Reference_Nos')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class UpdateManifestForm(BSModalForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
update_manifest.html
#showing the modal window body
<form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title">Update Manifest</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.product_name" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="submit-btn btn btn-primary">Update</button>
</div>
</form>
manifest_readonly.html
#showing the html rendered by the manifest view
{% extends 'base.html' %}
{% load humanize %}
{% block body %}
{% load staticfiles %}
<div class="container">
<div class="col-xs-12">
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
<center>{{ message }}</center>
</div>
{% endfor %}
{% endif %}
</div>
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
<label for="form.reference" class="formlabels">Case Total: </label><br>
<input type="text" value="{{ total_cases|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total CNF: </label><br>
<input type="text" value="{{ totalCNF|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total FOB: </label><br>
<input type="text" value="{{ totalFOB|intcomma }}" readonly>
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
<br>
<h4>Manifest</h4>
<div class="table-responsive">
<!--<table id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"-->
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th style="width:2%;"</th>
<th style="width:10%;">Cases</th>
<th style="width:60%;">Description</th>
<th style="width:10%;">Count</th>
<th style="width:10%">FOB</th>
<th style="width:10%">CNF</th>
</tr>
</thead>
<tbody>
{% for manifests in data %}
<tr>
<td>
<!-- Update book buttons -->
<button type="button" class="update-manifest btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'manifest_update' manifests.pk %}">
<span class="fa fa-pencil"></span>
</button>
</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.product_name}}</td>
<td>{{ manifests.count}}</td>
<td>{{ manifests.FOB}}</td>
<td>{{ manifests.CNF}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
Subit Manifest
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="jquery.min.js"></script>
<script src="jquery.fulltable.js"></script>
<script src="script.js"></script>
<script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
<script>
$(function () {
$(".update-manifest").each(function () {
$(this).modalForm({formURL: $(this).data('id')});
});
});
</script>
{% endblock %}
jquery.bootstrap.modal.forms.js
(function ($) {
// Place the form at formURL to modalContent element of modal with id=modalID
var newForm = function (modalID, modalContent, modalForm, formURL, successURL, errorClass) {
$(modalContent).load(formURL, function () {
$(modalID).modal('toggle');
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
});
};
// Add AJAX validation to the modalForm
var ajaxSubmit = function (modalID, modalContent, modalForm, successURL, errorClass) {
$(modalForm).submit(function (event) {
// Prevent submit and POST form to url using AJAX
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
// Serialize form data
data: $(this).serialize(),
success: function (response) {
// Update form with errors after unsuccessful POST request
// Django form.is_valid() = False
if ($(response).find(errorClass).length > 0) {
$(modalID).find(modalContent).html(response);
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
}
// Hide modal after successful POST request when & redirect to successURL
else {
$(modalID).modal("hide");
window.location.href = successURL;
}
}
});
});
};
$.fn.modalForm = function (options) {
// Default settings
var defaults = {
modalID: "#modal",
modalContent: ".modal-content",
modalForm: ".modal-content form",
formURL: null,
successURL: "/",
errorClass: ".invalid"
};
// Extend default settings with provided options
var settings = $.extend(defaults, options);
return this.each(function () {
$(this).click(function (event) {
newForm(settings.modalID,
settings.modalContent,
settings.modalForm,
settings.formURL,
settings.successURL,
settings.errorClass);
event.preventDefault();
});
});
};
}(jQuery));

Related

Django-Vue error "Failed to mount app: mount target selector returned null."

Thanks for looking into my problem, I am a beginner with Django and Vue your assistance with this wil be extremely helpful. I am working on a Job portal and created the job search functionality in Django as backend for the same I have an app called job into my Django project. The browser Js console gives this error Failed to mount app: mount target selector returned null. For this app I have an add job view, through which an employer adds the jobs. For this I'm using Vue for validation and showing any errors if any non-null fields are not entered by the employer account. So this is not how it was supposed to look,Unexpected results snap shot so as you can see it wasn't supposed to give me [[error]] and company_size instead The company size is missing as per the Vue AddJobApp, given below. Also if were to add # within mount-function-createapp within Vue-AddJobApp, the page entirely disappears (blank page). what am I doing wrong here?
adding # in AddJob.mount() function is making the page go blank a
Add job template
{% extends 'core/base.html' %}
{% block content %}
<div id="add-job-app">
<h1 class="title"> Add Job</h1>
<form action="." method="POST" v-on:submit="validateForm">
{% csrf_token %}
{% if form.errors %}
{% for error in form.errors %}
<div class="notification is-danger">
{{ error }}
</div>
{% endfor %}
{% endif %}
<div class="notification is-danger" v-if ="error.length" >
<p v-for="error in errors" >
[[ error ]]
</p>
</div>
<div class="field">
<label for="">Title</label>
<div class="control">
<input class="input" type="text" name="title" id="id_title" v-model= "title">
</div>
</div>
<div class="field">
<label for="">Short description</label>
<div class="control">
<textarea name="short_description" id="id_short_description" class="textarea" v-model= "short_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Long description</label>
<div class="control">
<textarea name="long_description" id="id_long_description" class="textarea" v-model= "long_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Company name</label>
<div class="control">
<input class="input" type="text" name="company_name" id="id_company_name" v-model= "company_name" >
</div>
</div>
<div class="field">
<label for="">Company address</label>
<div class="control">
<input class="input" type="text" name="company_address" id="id_company_address" v-model= "company_address">
</div>
</div>
<div class="field">
<label for="">Company zipcode</label>
<div class="control">
<input class="input" type="text" name="company_zipcode" id="id_company_zipcode" v-model= "company_zipcode">
</div>
</div>
<div class="field">
<label for="">Company place</label>
<div class="control">
<input class="input" type="text" name="company_place" id="id_company_place" v-model= "company_place">
</div>
</div>
<div class="field">
<label for="">Company Country</label>
<div class="control">
<input class="input" type="text" name="company_country" id="id_company_country" v-model= "company_country">
</div>
</div>
<div class="field">
<label for="">Company Size</label>
<div class="control">
<div class="select">
<select name="company_size" v-model = "company_size">
<option value="">Choose Size</option>
<option value="size_1_9">1-9</option>
<option value="size_10_49">10-49</option>
<option value="size_50_99">50-99</option>
<option value="size_100">100+</option>
</select>
</div>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-success">Submit</button>
</div>
</div>
</form>
</div>
{% endblock %}
{% block scripts %}
<script >
const AddJobApp = {
data() {
return {
title:'',
company_name:'',
short_description:'',
company_size:'',
errors:[]
}
},
delimiters:['[[',']]'],
methods :{
validateForm(e){
this.errors = []
if( this.title ===''){
this.errors.push('The title field is missing')
}
if( this.short_description ===''){
this.errors.push('The short description field is missing')
}
if( this.company_name ===''){
this.errors.push('The company name field is missing')
}
if( this.company_size ===''){
this.errors.push('The company size is missing')
}
if(this.errors.length){
e.preventDefault()
return false
}else{
return true
}
}
}
}
Vue.createApp(AddJobApp).mount('add-job-app');
</script>
{% endblock %}
my views.py file inside of job app
from apps.job.forms import AddJobForm, ApplicationForm
from django.shortcuts import redirect, render
from .models import Job
from django.contrib.auth.decorators import login_required
from apps.notification.utilities import create_notification
def job_detail(request,job_id):
job = Job.objects.get(pk=job_id)
return render(request, 'job/job_detail.html',{'job':job})
def search(request):
return render(request,'job/search.html')
#login_required
def apply_for_job(request,job_id):
job = Job.objects.get(pk=job_id)
if request.method=='POST':
form = ApplicationForm(request.POST)
if form.is_valid():
application = form.save(commit=False)
application.job = job
application.created_by = request.user
application.save()
create_notification(request, job.created_by ,'application',extra_id=application.id)
return redirect('dashboard')
else:
form = ApplicationForm()
return render(request,'job/apply_for_job.html',{'form':form,'job':job})
#login_required
def add_job(request):
if request.method=='POST':
form = AddJobForm(request.POST)
if form.is_valid():
job = form.save(commit=False)
job.created_by = request.user
job.save()
return redirect('dashboard')
else:
form = AddJobForm()
return render(request,'job/add_job.html',{'form':form})

Django pop up modal after Inserting/updating data

I've been searching in google and SO about pop up message when user submit but that doesnt work when i apply it to my code, I just want that if the user update/insert data, a pop up modal message appears
I have this form in my html
<form method="post" id="myform" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %}
<table id="blacklistgrids" border="2px">
<tr>
{% for v in table.0 %}
{% if forloop.first %}
<th id="thupdate">{{v}}</th>
{% else %}
<th ><input type="text" name="updatedate" value="{{ v }}"></th>
{% endif %}
{% endfor %}
<th hidden></th>
<th data-id='headerss' id='headerave'>Average</th>
</tr>
<tbody>
{% for row in table|slice:"1:" %}
<tr class="tr2update">
<td><input type="text" value="{{row.0}}" name="students" hidden>{% for n in teacherStudents %}{{n.Students_Enrollment_Records.Student_Users}}{% endfor %}</td>
<td class="tdupdate" hidden><input type="text" hidden></td>
{% for teacher in students %}
<input type="hidden" name="id" value="{{teacher.id}}"/>
<td>
<input type="text" data-form-field="{{teacher.id}}" name="oldgrad" class="oldgrad" value="{{teacher.Grade|floatformat:'2'}}"/>
</td>
{% endfor %}
{% for avg in average %}
<td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" value="{{average.average_grade|floatformat:'2'}}" readonly/></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="buttons">
<input type="submit" value="&nearrow; Update" class="save" formaction="/updategrades/">
</div>
</form>
<script>
if (typeof jqXhr.success != 'undefined') {
$('#thanksModal').modal('show');
} else {
$('#myform').html(jqXhr);
}
</script>
and this is my views.py
import json
def updategrades(request):
/some logic/
return HttpResponse(json.dumps({"success":True}), content_type="application/json")
you could use ajax and bootstrap modal,
crate a general modal somewhere in your html page(I usually have it in my base.html so it will be included in all pages) then submit your from by using ajax then ajax will provide success or error function regarding the response will receive from server-side. put that message in the modal. an example is:
somewhere inside base.html
<!-- Info General modal -->
<div id="general_modal" class="modal fade " >
<div class="modal-dialog ">
<div class="modal-content ">
<div class="modal-header bg-info">
<h6 class="modal-title">Info header</h6>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!-- Empty will be field by Js -->
</div>
</div>
</div>
</div>
<!-- /info General modal -->
js and ajax function
$("#your-form").on('submit',function(e){
e.preventDefault();
var ajax_link = this.getAttribute("data-ajax-link");
var target = this.getAttribute("data-target");
var title = this.getAttribute("data-modal-title");
var size = this.getAttribute("data-modal-size");
var bg = this.getAttribute("data-modal-content-bg");
// $(target+" .modal-body").load(ajax_link);
$.ajax({
url:ajax_link,
type:'POST',
// data: $("#your-form-feilds").serialize(),
success: function (response){
$(target+" .modal-body").html(response);
},
/*
error:function (response){
new PNotify({
title: 'oops',
text:' Unable to load',
type: 'error'
});
}
*/
});
$(target+" .modal-content").addClass(bg);
$(target+" .modal-title").html(title);
$(target+" .modal-dialog").removeClass().addClass("modal-dialog");
$(target+" .modal-dialog").addClass(size);
});
html form
<form action="." method="post" id="your-form" class="btn btn-info modal-ajax-load"
data-ajax-link="url"
data-toggle="modal"
data-modal-title="tilte"
data-target="#general_modal">
ofcurse you need to modify this answer to create the functions you need

Get pk_id using function based view

I'm having a problem in getting the pk in my template. When I select a record it always returns the last pk ID. Btw, I'am using functional base view. Here's my collection.html:
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
<table class="table" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Download</th>
</tr>
</thead>
<tbody>
{% for collectionlist in collection %}
<tr>
<td>{{ collectionlist.id }}</td>
<td>{{ collectionlist.sqa_name }}</td>
<td>{{ collectionlist.status }}</td>
<td class="center"><center><button type="button" class="btn btn-link" data-toggle="modal" data-target="#myModaldl{{ collectionlist.id }}" ><span class="glyphicon glyphicon-download-alt"></span></button></center></td>
</tr>
<div class="modal fade collectClass" id="myModaldl{{ collectionlist.id }}" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Single Collect</h3>
</div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label for="inputSQAID" class="col-sm-3 control-label">SQA Name</label>
<div class="col-sm-8">
<input type="hidden" name="pk_id" id="pk_id" value="{{ collectionlist.id }}">
<input type="text" class="form-control" name="singlecollect" value="{{ collectionlist.sqa_name }}" id="inputSQAID">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" name="single_dl">Download</button>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
</form>
Here's my views.py:
def collection(request):
context = {
'collection': DataCollection.objects.all(),
'title': 'Data Collection',
}
return render(request, 'data_collection/collection.html', context)
def single_collect(request):
if request.method == 'POST':
pkid = request.POST.get('pk_id')
print(pkid)
all_data = DataCollection.objects.all()
return render(request, 'data_collection/collection.html', {'title' : 'Data Collection', 'data': all_data})
In my views.py, I just want first to print the pk ID of the item/record I selected in my table using the modal. But, it's always getting the last record in my database.
This is because you have a single <form> tag with all the DataCollection rows inside. You should have individual forms for each one, i.e.:
{% for collectionlist in collection %}
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
...
</form>
{% endfor %}

Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicles_app/(?P<post_id>[0-9]+)/update_post/$']

I have searched a lot, but couldn't find a solution. There are a lot of related questions being asked before and I think there's no mistake but there's still an error.
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicles_app/(?P<post_id>[0-9]+)/update_post/$']
Here is my index.html
{% for obj in context %}
<div class="container" style="padding-left:240px; padding-right:0px; width: 78%; margin-bottom:30px;">
<div class="well" style=" background-color: rgb(220, 220, 220);">
<div class="media">
<div class="media-body">
<div class="list-group">
<div class="d-flex w-100 justify-content-between">
<h1 class="media-heading" style="margin-top:20px; margin-bottom:20px; color: black;">{{ obj.title }}</h1>
{% for img in obj.postpicture_set.filter %}
<div class="w3-content" style="max-width:800px">
{% if img.image %}
<img style="margin-bottom:30px; float: right" class="mySlides" src="{{ img.image.url }}" width="200" height="180">
{% endif %}
</div>
{% endfor %}
<p> {{ obj.details }} </p>
<ul class="list-inline list-unstyled">
<li><span><i class="glyphicon glyphicon-calendar"></i> {{ obj.date }} </span></li>
<li>|</li>
<span><i></i> {{ obj.brand }} </span>
<li>|</li>
<span><i></i> {{ obj.city }} </span><br>
<form action="{% url 'vehicles_app:data' obj.id %}" method="post">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}">
<input type="hidden" name="usr_id" value="{{ obj.user_id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" class="btn btn-primary" value="Details"</td></form>
{% if request.user == obj.user or request.user.is_superuser %}
<form action="{% url 'vehicles_app:file-delete' obj.id %}" method="post" style="display: inline;">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" value="Delete" class="btn btn-danger btn-sm"</td></form>
<form action="{% url 'vehicles_app:update' obj.id %}" method="post" style="display: inline;">{% csrf_token %}<input type="hidden" name="post_id" value="{{ obj.id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" value="Update" class="btn btn-default btn-sm"</td></form>
{% else %}
{% endif %}
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Here is views.py
def update_post(request, post_id):
ImageFormSet = modelformset_factory(
PostPicture,
form=AddPictures,
extra=10,
min_num=1
)
post_form = get_object_or_404(Posts, pk=post_id)
if request.method == "POST":
form = AddFile(request.POST, instance=post_form)
formset = ImageFormSet(
queryset=PostPicture.objects.filter(
post=post_id
)
)
if form.is_valid() and formset.is_valid():
form.save()
for form in formset:
if form:
image = form['image']
photo = PostPicture(post=form, image=image)
photo.save()
messages.success(
request, 'Post submitted Successfully!'
)
return render(
request,
'vehicles_app/update_post.html',
{
'form': form,
'formset': formset,
'post_form':post_form
}
)
else:
print(form.errors, formset.errors)
else:
form = AddFile()
formset = ImageFormSet(
queryset=PostPicture.objects.none()
)
return render(
request,
'vehicles_app/update_post.html',
{
'form': form,
'formset': formset,
'post_form':post_form
}
)
Here is the url for my update, only update is not working, but other things like data and delete are working fine.
urlpatterns = [
url(r'^signUp/$', views.signUp, name='signUp'),
url(r'^user_login/$', views.user_login, name='user_login'),
url(r'^addfile/$', views.addfile, name='addfile'),
url(r'^(?P<pk>[0-9]+)/delete/$', views.FileDelete.as_view(), name='file-delete'),
url(r'^(?P<post_id>[0-9]+)/data/$', views.data, name='data'),
url(r'^(?P<post_id>[0-9]+)/update_post/$', views.update_post, name='update'),
url(r'^myposts/$', views.myposts, name='myposts'),
url(r'^received/$', views.received, name='received'),
url(r'^received_files/$', views.received_files, name='received_files'),
]
here is my update_post.html
{% extends "vehicles_app/index.html" %}
{% block body_block %}
{% load staticfiles %}
<html>
<body>
<div class="container" id="addfile_form" style="margin- left:200px; width: 78%;">
<!-- <div class="col-xs-12 col-sm-4 col-md-6 col-sm-offset-2 col- md-offset-2"> -->
<div class="panel panel-default">
<div>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<h2 style="margin-left:100px;"> {{ message }} </h2>
{% endfor %}
</ul>
{% endif %}
</div>
<div class="panel-heading">
<b><h2 id="post_head" class="panel-title">Update Post here!</h2>
</b>
</div>
<div class="panel-body">
<form id="post_form" method="post" action="{% url
'vehicles_app:update_post' post_id %}"
enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="form-group">
<div style="float: left; width: 50%">
<label for="title">Ad Title</label>
</div>
<div class="title" style="float: right; width: 45%">
<input type="text" name="title" placeholder="Type Here"
value='{{ form.title.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="city">City</label>
</div>
<div class="city" style="float: right; width: 45%">
<select name="city" value='{{ form.city.value }}'>
<option selected="selected"
value="islamabad">Islamabad</option>
<option value="karachi">Karachi</option>
<option value="lahore">Lahore</option>
<option value="peshawar">Peshawar</option>
<option value="quetta">Quetta</option>
<option value="multan">Multan</option>
<option value="faisalabad">Faisalabad</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="price">Price</label>
</div>
<div class="price" style="float: right; width: 45%">
<input type="text" name="price" placeholder="Type Here"
value='{{ form.price.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="brand">Brand</label>
</div>
<div class="brand" style="float: right; width: 45%">
<select name="brand" value='{{ form.brand.value }}'>
<option selected="selected"
value="honda">Honda</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="suzuki">Suzuki</option>
<option value="toyota">Toyota</option>
<option value="lexus">Lexus</option>
<option value="hyundai">Hyundai</option>
<option value="jeep">Jeep</option>
<option value="mazda">Mazda</option>
<option value="mitsubishi">Mitsubishi</option>
<option value="daewoo">Daewoo</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="modelyear">Model-Year</label>
</div>
<div class="modelyear" style="float: right; width: 45%">
<input type="text" name="modelyear"
placeholder="ie:1970-2018" value='{{ form.modelyear.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="condition">Condition</label>
</div>
<div class="condition" style="float: right; width: 45%">
<select name="condition" value='{{ form.condition.value
}}'>
<option selected="selected" value="new">NEW</option>
<option value="used">USED</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="mileage">Mileage</label>
</div>
<div class=mileage style="float: right; width: 45%">
<input type="text" name="mileage" placeholder="ie:50000"
value='{{ form.mileage.value }}' required>
</div>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="details">Type details here</label>
</div>
<div class="details" style="float: right; width: 45%">
<textarea name="details" rows="9" cols="45" value='{{
form.details.value }}' required></textarea>
</div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
{{ formset.management_form }}
{% if formset %}
{% for form in formset %}
{% if form %}
<table class="display" cellspacing="1" width="100%">
<tr>
<td>{{ form }}</td>
</tr>
</table>
{% endif %}
{% endfor %}
{% endif %}
<input type="submit" name="submit" value="Update" class="btn
btn-info" id="post_btn">
</form>
</div>
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</body>
</html>
{% endblock %}
The error is coming from this url tag in your update_post.html template.
<form id="post_form" method="post" action="{% url 'vehicles_app:update_post' post_id %}"
You get the error with arguments '('',)' in the error message because you haven't included post_id in the template context. You can add it with:
return render(request, 'vehicles_app/update_post.html', {
'form': form,
'formset': formset,
'post_form': post_form,
'post_id': post_id,
})
Remember to do this for GET and POST requests.

Django with Bootstrap-file-upload

I'm using a Django form to load an image and I'm using Bootstap-fileinput.
When the form has already been initialised with an image I want the image displayed immediately but it simple shows no image currently. How do I get the template to automatically show the file-input-exists version of the Bootstap HTML rather than the file-input-new version?
Forms.py :
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['image',]
widget = {
'image' : forms.FileInput(attrs={'class': 'form-control',
'id' : 'input-file'}),
}
My template has:
{{form.image}}
{{form.image.errors}}
This generates the following HTML whether the form contains an image or not
<div class="file-input file-input-new"><div class="file-preview ">
<div class="close fileinput-remove">×</div>
<div class="">
<div class="file-preview-thumbnails"></div>
<div class="clearfix"></div>
<div class="file-preview-status text-center text-success"></div>
<div class="kv-fileinput-error file-error-message" style="display: none;"></div>
</div>
</div>
<div class="kv-upload-progress hide"></div>
<div class="input-group ">
<div tabindex="500" class="form-control file-caption kv-fileinput-caption">
<div class="file-caption-name"></div>
</div>
<div class="input-group-btn">
<button type="button" tabindex="500" title="Clear selected files" class="btn btn-default fileinput-remove fileinput-remove-button"><i class="glyphicon glyphicon-trash"></i> Remove</button>
<button type="button" tabindex="500" title="Abort ongoing upload" class="btn btn-default hide fileinput-cancel fileinput-cancel-button"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button>
<div tabindex="500" class="btn btn-primary btn-file"><i class="glyphicon glyphicon-folder-open"></i> Browse …<input class="form-control" id="input-file" name="image" type="file" required=""></div>
</div>
</div>
** EDIT **
Thanks to help so far I now have the images showing, but if I try and resubmit the form I get a message that no file has been chosen. I need to pick this up as well.
I've added this JavaScript in order to display the image on loading.
<script>
$("#input-file").fileinput({
showUpload: false,
initialPreviewShowDelete: false,
{% if form.instance.image %}
initialPreview: [
"<img src='{{ form.instance.image.url }}' class='file-preview-frame'>",
],
initialPreviewConfig: [
{caption: "{{ form.instance.image.name}}",},
],
{% endif %}
});
</script>
I am getting the preview of saved database file by using this script
<script>
$(document).ready(function(){
$("#id_album_logo").fileinput({
showUpload: false,
showCaption: false,
browseClass: "btn btn-primary btn-lg",
fileType: "any",
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
overwriteInitial: false,
initialPreviewAsData: true,
{% if form.instance.album_logo %}
initialPreview: [
"{{ form.instance.album_logo.url }}",
],
initialPreviewConfig: [
{caption: "{{ form.instance.album_logo.name}}", width: "120px", url: "{$url}", key: 1},
],
{% endif %}
});
})
where id_album_logo is the id assigned to form input ,
initialPreview: [
"{{ form.instance.album_logo.url }}",
],
is the url of the image already saved in database
my models.py
class Album(models.Model):
user = models.ForeignKey(User)
album_logo=models.FileField(upload_to=upload_location)
my forms.html is
<div class="container-fluid">
<div class="row">
<div class="col-sm-6 col-md-6 col-lg-6 col-sm-offset-3 col-md-offset-3 col-lg-offset-3">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'form-template.html' %}
<div class="form-group">
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
and form-template.html is
{% for field in form %}
<div class="form-group djfr">
<label class="control-label">{{ field.label_tag }}</label>
{{ field }}
<span class="text-danger small">{{ field.errors }}</span>
</div>
{% endfor %}

Categories

Resources