view function isn't returning anything - python

The problem here is that when the form is posted the create_usecase function runs and then it redirects to another URL. This URL runs the quest function in the view and executes every line in the function but it doesn't make any return at all the create-usecase template stays as it is.
So the template is like this:
<form>
<div class="row">
<div class="input-field col s6 offset-s3">
<div class="row">
<div class="col m2 s4">
<p>Case name</p>
</div>
<div class="col m10 s8">
<input id="usecase_name" type="text" name="usecase_name" placeholder="Case name">
</div>
</div>
</div>
<div class="input-field col s6 offset-s3">
<select id="category-list">
<option value="" disabled selected>Choose your Category</option>
<option value="1">University/College</option>
<option value="2">Hospital</option>
<option value="3">Business Organizations</option>
</select>
<label>Categories</label>
</div>
</div>
<div id="subcategory-list" class="row">
<div class="col s6 offset-s3">
{% if data %}
<h6>Sub Category</h6>
{% for item in data %}
<div class="form-check">
<input class="form-check-input" onchange="subCategoryValue('{{ item.username }}')" type="radio" name="sub-category" id="{{ item.username }}" value="{{ item.username }}">
<label class="form-check-label" for="{{ item.username }}">
{{ item.username }}
</label>
</div>
{% endfor %}
{% endif %}
</div>
</div>
<div class="row center">
<button type="submit" id="nextBtn" class="btn waves-effect waves-light orange">Next</button>
</div>
</form>
<script type="text/javascript">
var flag = ''
function subCategoryValue(v) {
flag = v;
$('#nextBtn').show();
}
$(document).ready(function(){
$('#nextBtn').hide();
$('#category-list').change(function(e){
e.preventDefault();
if($('#usecase_name').val() !== '') {
$.ajax({
type: 'POST',
url: '/create-usecase/',
data: {
usecase_name: $('#usecase_name').val(),
category: $('#category-list').val(),
sub_category: '',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success:function(response) {
$('#subcategory-list').replaceWith($("#subcategory-list",response));
}
});
} else {
alert('Please fill the usecase field.')
}
});
});
$('#nextBtn').click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/create-usecase/',
data: {
usecase_name: $('#usecase_name').val(),
category: $('#category-list').val(),
sub_category: flag,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success:function() {
}
})
});
</script>
And the views:
def create_usecase(request):
if not request.user.is_authenticated:
return redirect('index')
else:
if request.method == 'POST':
if not request.POST['sub_category'] == '':
print(request.POST['sub_category'])
#create a use new use case or project in the database
request.session['usecase_name'] = request.POST['usecase_name']
request.session['category'] = request.POST['category']
request.session['sub_category'] = request.POST['sub_category']
return redirect('quest')
else:
users = User.objects.all()
return render(request, 'usecases/create-usecase.html', {'data': users})
else:
return render(request, 'usecases/create-usecase.html')
def quest(request):
print('questions!')
print('{} {} {} '.format(request.session['usecase_name'], request.session['category'], request.session['sub_category']))
return HttpResponse('test')
And the urls:
urlpatterns = [
path('create-usecase/quest/', views.quest, name='quest'),
path('create-usecase/', views.create_usecase, name='create_usecase'),
]
The console:
[17/May/2018 13:57:14] "GET /create-usecase/ HTTP/1.1" 200 4376
[17/May/2018 13:57:19] "POST /create-usecase/ HTTP/1.1" 200 5514
test1
[17/May/2018 13:57:23] "POST /create-usecase/ HTTP/1.1" 302 0
questions!
test 1 test1
[17/May/2018 13:57:23] "GET /create-usecase/quest/ HTTP/1.1" 200 4

Related

Django - Can't get the specific primary key (id) for an object in a list of objects

I am trying to get the specific pk of the selected object when the user accepts a delivery. My problem is that I'm getting only the first object's pk in the list every time. I want to get the pk of the selected object.
views:
#login_required(login_url="/signin/?next=/driver/")
def deliveries_available_page(request):
deliveries = Delivery.objects.filter(
status_of_delivery__in=[Delivery.DELIVERY_POSTED]
)
#When driver accept delivery then status of delivery changes to delivering
if request.method == 'POST':
delivery = get_object_or_404(Delivery, pk=request.POST.get('receipt_number'))
if delivery:
delivery.status_of_delivery = Delivery.DELIVERY_DELIVERING
delivery.driver = request.user.driver
messages.success(request, 'Delivery Accepted')
delivery.save()
return redirect(reverse('driver:deliveries_available'))
return render(request, 'driver/deliveries_available.html', {
"GOOGLE_API_MAP": settings.GOOGLE_API_MAP,
"del": deliveries
})
HTML:
<div class="d-flex flex-column h-100" style="padding-bottom: 50px">
<div id="map"></div>
{% if del %}
{% for d in del %}
<div class="card" id="delivery-popup">
<div class="card-body p-2">
<div class="details">
<div class="p-2">
<strong id="address"></strong>
<div>
<strong id="show-info"></strong>
</div>
<div>
<strong id="show-distance"></strong>
<strong id="show-duration"></strong>
</div>
<div>
<strong id="show-price"></strong>
<strong id="show-id"></strong>
</div>
<div>
<form method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-primary" name="accept">Accept</button>
<input type="hidden" value="{{ d.receipt_number }}" name="receipt_number">
</form>
</div>
{% if messages %}
{% for m in messages %}
{% if m.tags %}
<script>alert("{{ m }}")</script>
{% endif %}
{% endfor %}
{% endif %}
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
I need the specific pk so when user accept delivery, then the right delivery is accepted and removed from the map. Any help would be appreciated. Thanks.
I can get the specific pk by creating new url and passing it in the url but i want user to accept delivery on the map page.
script added to html
<script>
//Google map and using api to display deliveries on map and click event to show delivery details
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 53.350140, lng: -6.266155 },
zoom: 13,
});
fetch("{% url 'driver:available_deliveries' %}").then(response => response.json()).then(json => {
console.log(json);
for (let d = 0; d < json.deliveries.length; d++) {
const delivery = json.deliveries[d];
const position = { lat: delivery.delivery_address_latitude, lng: delivery.delivery_address_longitude };
const show_on_map = new google.maps.Marker
({
position,
map,
});
new google.maps.InfoWindow({
content: "<small><strong>" + delivery.address + "<medium><br>€" + delivery.price
}).open(map, show_on_map);
show_on_map.addListener("click", () => {
PopUpDelivery(delivery);
})
}
})
}
function PopUpDelivery(delivery) {
$("#delivery-popup").css("display", "block");
$("#address").html(delivery.address);
$("#show-distance").html(delivery.distance + " Km");
$("#show-duration").html(delivery.duration + " Mins");
$("#show-price").html("€ " + delivery.price);
$("#show-info").html("Info : " + delivery.information);
$("#show-id").html("Pk : " + delivery.receipt_number)
}
Keep id unique in html document
The id in an HTML document must be unique within each page source:
The id global attribute defines an identifier (ID) which must be
unique in the whole document. Its purpose is to identify the element
when linking (using a fragment identifier), scripting, or styling
(with CSS).
What I think may have occurred is that since you have many cards in each page, all with the same id's, you were just getting the first one. While your solution works, I think it might be better to give each id a unique value, which you can do simply by appending the receipt_number, or any unique field to the id names. With this, you may not need the function getTag. Here is what I mean:
html
<div class="d-flex flex-column h-100" style="padding-bottom: 50px">
<div id="map"></div>
{% if del %}
{% for d in del %}
<div class="card" id="delivery-popup{{ d.receipt_number }}">
<div class="card-body p-2">
<div class="details">
<div class="p-2">
<strong id="address{{ d.receipt_number }}"></strong>
<div>
<strong id="show-info{{ d.receipt_number }}"></strong>
</div>
<div>
<strong id="show-distance{{ d.receipt_number }}"></strong>
<strong id="show-duration{{ d.receipt_number }}"></strong>
</div>
<div>
<strong id="show-price{{ d.receipt_number }}"></strong>
<strong id="show-id{{ d.receipt_number }}"></strong>
</div>
<div>
<form method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-primary" name="accept">Accept</button>
<input type="hidden" value="{{ d.receipt_number }}" name="receipt_number">
</form>
</div>
{% if messages %}
{% for m in messages %}
{% if m.tags %}
<script>alert("{{ m }}")</script>
{% endif %}
{% endfor %}
{% endif %}
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
script
<script>
//Google map and using api to display deliveries on map and click event to show delivery details
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 53.350140, lng: -6.266155 },
zoom: 13,
});
fetch("{% url 'driver:available_deliveries' %}").then(response => response.json()).then(json => {
console.log(json);
for (let d = 0; d < json.deliveries.length; d++) {
const delivery = json.deliveries[d];
const position = { lat: delivery.delivery_address_latitude, lng: delivery.delivery_address_longitude };
const show_on_map = new google.maps.Marker
({
position,
map,
});
new google.maps.InfoWindow({
content: "<small><strong>" + delivery.address + "<medium><br>€" + delivery.price
}).open(map, show_on_map);
show_on_map.addListener("click", () => {
PopUpDelivery(delivery);
})
}
})
}
function PopUpDelivery(delivery) {
let pk = delivery.receipt_number
$("#delivery-popup"+pk).css("display", "block");
$("#address"+pk).html(delivery.address);
$("#show-distance"+pk).html(delivery.distance + " Km");
$("#show-duration"+pk).html(delivery.duration + " Mins");
$("#show-price"+pk).html("€ " + delivery.price);
$("#show-info"+pk).html("Info : " + delivery.information);
$("#show-id"+pk).html("Pk : " + delivery.receipt_number)
}
Solved:
Got the specific pk, when i click on a delivery it gets the right pk, code below if anyone has the same problem:
script
function PopUpDelivery(delivery) {
$("#delivery-popup").css("display", "block");
$("#address").html(delivery.address);
$("#show-distance").html(delivery.distance + " Km");
$("#show-duration").html(delivery.duration + " Mins");
$("#show-price").html("€ " + delivery.price);
$("#show-info").html("Info : " + delivery.information);
$("#show-id").html("Pk : " + delivery.receipt_number);
var input_tag = getTag('getpk');
input_tag.value = delivery.receipt_number;
}
function getTag(id){
return document.getElementById(id);
}
html
<button type="submit" class="btn btn-primary" name="accept">Accept</button>
<input type="hidden" id="getpk" value="" name="receipt_number">

How to resolve reverse match error in django

I'm new to Django and I cannot understand why this error is popping up:
django.urls.exceptions.NoReverseMatch: Reverse for 'updater' with no arguments not found. 1 pattern(s) tried: ['update/(?P<updating>[0-9]+)$']
[26/Jul/2020 19:05:05] "GET /update/2 HTTP/1.1" 500 127513
my urls:
urlpatterns=[
path('update/<int:updating>',views.update,name='updater'),
]
the html page:
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<title>NEW PRODUCT</title>
</head>
<body>
<div class="bg-contact2" style="background-image: url('images/bg-01.jpg');">
<div class="container-contact2">
<div class="wrap-contact2">
<form class="contact2-form validate-form" method="post" action="{%url 'updater' %}" enctype="multipart/form-data">
{% csrf_token %}
<span class="contact2-form-title">
Provide Product details Below
</span>
<div class="wrap-input2 validate-input" data-validate="type is required">
<input class="input2" type="text" name="type" value="{{details.product_type}}">
<span class="focus-input2" data-placeholder="PRODUCT-TYPE"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "Name is required">
<input class="input2" type="text" name="name" value="{{details.product_name}}">
<span class="focus-input2" data-placeholder="PRODUCT NAME"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "description is required">
<textarea class="input2" name="description">{{details.product_description}}</textarea>
<span class="focus-input2" data-placeholder="PRODUCT DESCRIPTION"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "Price is required">
<input class="input2" type="number" name="price" value="{{details.product_price}}">
<span class="focus-input2" data-placeholder="PRICE"></span>
</div>
<div class="wrap-input2 validate-input" data-validate = "Picture is required">
<label >product sample picture</label>
<input class="input2" type="file" name="picture">
<span class="focus-input2" data-placeholder=""></span>
</div>
<div class="container-contact2-form-btn">
<div class="wrap-contact2-form-btn">
<div class="contact2-form-bgbtn"></div>
<button class="contact2-form-btn">
Update Product Listing
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
my views:
def update (request,updating):
if request.method=='POST':
product_details=product_info.objects.get(id=updating)
product_details.product_type=request.POST.get('type')
product_details.product_name=request.POST.get('name')
product_details.product_description=request.POST.get('description')
product_details.product_price=request.POST.get('price')
if (len(request.FILES) != 0):
image = request.FILES['picture']
product_details.product_pic = image
product_details.save()
alldetails = product_info.objects.all()
return render(request, 'adminside/editingpage.html', {'editing_details': alldetails})
else:
product_details = product_info.objects.get(id=updating)
return render(request,'adminside/updating.html',{'details':product_details})
def update (request,updating) :
if request.method=='POST' :
product_details=product_info.objects.get(id=updating)
product_details.product_type=request.POST.get('type')
product_details.product_name=request.POST.get('name')
product_details.product_description=request.POST.get('description')
product_details.product_price=request.POST.get('price')
if (len(request.FILES) != 0):
image = request.FILES['picture']
product_details.product_pic = image
product_details.save()
alldetails = product_info.objects.all()
return render(request, 'adminside/editingpage.html', {'editing_details': alldetails})
else:
product_details = product_info.objects.get(id=updating)
return render(request,'adminside/updating.html',{'details':product_details})
def update (request,updating):
if request.method=='POST':
product_details=product_info.objects.get(id=updating)
product_details.product_type=request.POST.get('type')
product_details.product_name=request.POST.get('name')
product_details.product_description=request.POST.get('description')
product_details.product_price=request.POST.get('price')
if (len(request.FILES) != 0):
image = request.FILES['picture']
product_details.product_pic = image
product_details.save()
alldetails = product_info.objects.all()
return render(request, 'adminside/editingpage.html', {'editing_details': alldetails})
else:
product_details = product_info.objects.get(id=updating)
return render(request,'adminside/updating.html',{'details':product_details})
I think it has something to do with passing the id of the product in the url, but I'm not sure about how to resolve it.
you have not put any argument in the url you have to put argument in the form action for updating like this
<form class="contact2-form validate-form" method="post" action="{%url 'updater' updating='ANYVALUE' %}" enctype="multipart/form-data">
because you haven't specify any value your url is not matching
This urlpattern update/ takes an int route parameter
path('update/<int:updating>',views.update,name='updater'),
In your template, you're trying to reverse updater with no included argument. So it's trying to reverse to a urlpattern of update/ which it can't find because you only have a path for update/<int:updating>
{%url 'updater' %}
You will need to change it to the following as you gave the context object the name details and you can access
{%url 'updater' details.id %}

HTML form rows disappear when changing one particular form field

I am working on a feature that allow to update the properties of a node (name etc.). So in my changeservice.html I first populate a list with all nodes. Then depending on the selection an AJAX function is fetching all node details and pre-populates a form. Now everything works fine, I can change the values of all fields but one input in particular - service_name . Then for some reason all other fields disappear from the screen and are not even submitted with the POST afterwards, resulting in the following error:
File "C:\Users\nb67ab\Envs\virtualobeya4dec\virtualobeya\views.py", line 437, in changeservice features_1 = request.form['features_1']
File
"C:\Users\nb67ab\Envs\virtualobeya4dec\Lib\site-packages\werkzeug\datastructures.py",
line 443, in getitem raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser
(or proxy) sent a request that this server could not understand.
KeyError: 'features_1'
My HTML looks like:
{% extends "layouts/layout.html" %}
{% block content %}
<div class="main-content">
<!-- Basic Form area Start -->
<div class="container-fluid">
<!-- Form row -->
<div class="row">
<div class="col-lg-12 ">
<div class="card">
<div class="card-body">
<h4 class="card-title">Change Service</h4>
<div class="form-row">
<div class="form-group col-md-4">
<label for="service_selected" class="col-form-label">Select Service or PB</label>
<select id="service_selected" name="platform_selected" class="form-control">
<option>Choose</option>
{% for x in services %}
<option value="{{x.name}},{{ x.type }},{{ x.pname }}">{{ x.name }},{{ x.type }},{{ x.pname }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</div>
<div class="card" id="service_details" style="display: none">
<div class="card-body">
<form action="{{ url_for('changeservice') }}" method="post">
<div class="form-row">
<div id="service_name_old" class="form-group col-md-4" style="display: none">
<label for="servicenameold" class="col-form-label">Service Name Old</label>
<input type="text" class="form-control" name="servicenameold" id="servicenameold" placeholder="">
<label for="domainnameold" class="col-form-label">Domain Name Old</label>
<input type="text" class="form-control" name="domainnameold" id="domainnameold" placeholder="">
<label for="platformnameold" class="col-form-label">Platform Name Old</label>
<input type="text" class="form-control" name="platformnameold" id="platformnameold" placeholder="">
</div>
<div class="form-group col-md-3">
<div class="custom-control custom-radio">
<input type="radio" id="EPS" name="type" class="custom-control-input" value="EPS" checked>
<label class="custom-control-label" for="EPS">Exposed Platform Service</label>
</div>
</div>
<div class="form-group col-md-3">
<div class="custom-control custom-radio">
<input type="radio" id="ESPB" name="type" class="custom-control-input" value="ESPB">
<label class="custom-control-label" for="ESPB">Exposed Supplied Product Build</label>
</div>
</div>
<div class="form-group col-md-3">
<div class="custom-control custom-radio">
<input type="radio" id="ETES" name="type" class="custom-control-input" value="ETES">
<label class="custom-control-label" for="ETES">Exposed Tied Engineering Support</label>
</div>
</div>
<div class="form-group col-md-3">
<div class="custom-control custom-radio">
<input type="radio" id="ET" name="type" class="custom-control-input" value="ET">
<label class="custom-control-label" for="ET">Exposed Training&Counseling</label>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="selected_domain" class="col-form-label">Select domain where service belongs</label>
<select id="selected_domain" name="selected_domain" class="form-control">
<option>Choose</option>
{%for x in domain%}
<option value="{{x}}">{{x}}</option>
{%endfor%}
</select>
</div>
<div class="form-group col-md-6">
<label for="selected_platform" class="col-form-label">Select platform exposing the service</label>
<select name="selected_platform" id="selected_platform" class="form-control">
<option>Choose</option>
{%for x in platform%}
<option value="{{x}}">{{x}}</option>
{%endfor%}
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label class="col-form-label">Service Name</label>
<input type="text" class="form-control" name="service_name" id="service_name" placeholder="Service Name">
</div>
</div>
<div class="form-row">
<div id="features" class="form-group col-md-3">
</div>
<div id="options" class="form-group col-md-3">
</div>
<div id="qualities" class="form-group col-md-3">
</div>
<div id="aspects" class="form-group col-md-3">
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Change Service</button>
</div>
<div class="message-box">
{% for message in get_flashed_messages() %}
<div class="flash">{{ message }}</div>
{% endfor %}
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script src="{{ url_for('static', filename='js/ajax.js') }}"></script>
{% endblock %}
The Ajax Script looks like:
$("#service_selected").on('change', function(){
$.ajax(
{
url: '/returnservicedetails',
data:{
serviceselect: $("#service_selected").val()
},
success: function (data,status,xhr) { // success callback function
if (data.length > 0){
var js = JSON.parse(data);
console.log(data);
var servicename = js[0]['name'];
var type = js[0]['type'];
var domain=js[0]['dname'];
var platform=js[0]['pname'];
var features=js[0]['features'];
var serviceoptions = js[0]['options'];
var qualities=js[0]['qualities'];
var aspects = js[0]['aspects'];
$('#servicenameold').val(servicename);
$('#service_name').val(servicename);
if (type=='EPS') {
$('#EPS').prop('checked',true);
$(':radio:not(:checked)').attr('disabled', true);
}
else {
if (type=='ESPB') {
$('#ESPB').prop('checked',true);
$(':radio:not(:checked)').attr('disabled', true);
}
else {
if (type=='ETES') {
$('#ETES').prop('checked',true)
$(':radio:not(:checked)').attr('disabled', true);
}
else {
$('#ET').prop('checked',true)
$(':radio:not(:checked)').attr('disabled', true);
}
}
}
$('#selected_domain').val(domain);
$('#domainnameold').val(domain);
$('#selected_platform').val(platform);
$('#platformnameold').val(platform)
var features1 = '<label class="col-form-label">Features</label>';
for (var j = 0; j < features.length; j++) {
features1 += '<input type="text" class="form-control" name="features_' + (j + 1) + '" id="features_' + (j + 1) + '" placeholder="" value="' + features[j]+'" >';
}
$("#features").empty('').append(features1);
var serviceoptions1 = '<label class="col-form-label">Options</label>';
for (var j = 0; j < serviceoptions.length; j++) {
serviceoptions1 += '<input type="text" class="form-control" name="options_' + (j + 1) + '" id="options_' + (j + 1) + '" placeholder="" value="' + serviceoptions[j]+'" >';
}
$("#options").empty('').append(serviceoptions1);
var qualities1 = '<label class="col-form-label">Qualities</label>';
for (var j = 0; j < qualities.length; j++) {
qualities1 += '<input type="text" class="form-control" name="qualities_' + (j + 1) + '" id="qualities_' + (j + 1) + '" placeholder="" value="' + qualities[j]+'" >';
}
$("#qualities").empty('').append(qualities1);
var aspects1 = '<label class="col-form-label">Aspects</label>';
for (var j = 0; j < aspects.length; j++) {
aspects1 += '<input type="text" class="form-control" name="aspects_' + (j + 1) + '" id="aspects_' + (j + 1) + '" placeholder="" value="' + aspects[j]+'" >';
}
$("#aspects").empty('').append(aspects1);
$("#service_details").show()
}
else {
$("#service_details").hide()
}
},
error: function (jqXhr, textStatus, errorMessage) { // error callback
}
});
})
The Python endpoint looks like:
#app.route('/changeservice', methods=["GET","POST"])
def changeservice():
user=User(session["username"])
if request.method=="POST":
servicenameold=request.form['servicenameold']
domainnameold=request.form['domainnameold']
platformnameold=request.form['platformnameold']
newservicename=request.form['service_name']
domainnamenew=request.form['selected_domain']
platformnamenew=request.form['selected_platform']
stype=request.form['type']
features_1 = request.form['features_1']
features_2 = request.form['features_2']
features_3 = request.form['features_3']
features_4 = request.form['features_4']
options_1 = request.form['options_1']
options_2 = request.form['options_2']
options_3 = request.form['options_3']
options_4 = request.form['options_4']
qualities_1 = request.form['qualities_1']
qualities_2 = request.form['qualities_2']
qualities_3 = request.form['qualities_3']
qualities_4 = request.form['qualities_4']
aspects_1 = request.form['aspects_1']
aspects_2 = request.form['aspects_2']
aspects_3 = request.form['aspects_3']
aspects_4 = request.form['aspects_4']
features_all = [features_1, features_2, features_3, features_4]
options_all = [options_1, options_2, options_3, options_4]
qualities_all = [qualities_1, qualities_2, qualities_3, qualities_4]
aspects_all = [aspects_1, aspects_2, aspects_3, aspects_4]
if not newservicename or not domainnamenew or not platformnamenew:
flash("You must specify Service Name, Domain and Platform")
else:
nodeid=Services.returnexposedID(servicenameold,stype,platformnameold)
servicedetails=Services.returnExposedDetails(nodeid)
if servicedetails[0]['name']==newservicename and servicedetails[0]['features']==features_all and servicedetails[0]['options']==options_all and servicedetails[0]['qualities']==qualities_all and servicedetails[0]['aspects']==aspects_all and servicedetails[0]['dname']==domainnamenew and servicedetails[0]['pname']==platformnamenew:
flash("No changes were made")
else:
user.unhookServiceFromPandD(nodeid)
user.updateExposedProperties(nodeid,newservicename,domainnamenew,platformnamenew,features_all,options_all,qualities_all,aspects_all)
user.updateExposedsurroundings(nodeid)
platforms = Platforms.listAllplatforms()
domains = Domains.listdomains()
services=Services.listallexposed()
return render_template("changeservice.html",services=services,platform=platforms,domain=domains)
I forgot that all variables in Javascript are global, I had another function listening on a field with the same name.

Reverse for `view` with arguments '('',)' not found. 1 pattern(s) tried: `[u'bms/update/(?P<id>[0-9]+)/$']`

This is my update view which I'm using to get pre-populated form. Although this is also not working.
def update(request, id):
item = get_object_or_404(BookEntry, id=id)
if request.method=="POST":
form = UpdateForm(request.POST, instance=item)
if form.is_valid():
post=form.save(commit=False)
post.save()
return HttpResponseRedirect(reverse('bms:index'), id)
else:
form=EntryForm(instance=item)
return HttpResponseRedirect(reverse('bms:index'), id)
return render(request, 'index.html', {'form':form})
This is my urls.py
url(r'^update/(?P<id>[0-9]+)/$', views.update, name='update'),
This is the error that I'm getting again and again:
NoReverseMatch at /bms/
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: [u'bms/update/(?P[0-9]+)/$']
I'm not sure if passing the url in right way. This is what i'm doing:
<form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST">
When I look at traceback, it's showing something's wrong in above line and this line:
return render(request, "bms/index.html", context)
This is my index view:
def index(request):
context = {}
book_detail = BookEntry.objects.all()
context.update({
'book_detail': book_detail
})
response = {"status": False, "errors": []}
if request.is_ajax():
id = request.POST['id']
csrf_token = request.POST['csrfmiddlewaretoken']
response = {}
response['status'] = False
book = BookEntry.objects.filter(id=id).first()
context = {
"book": book,
"csrf_token": csrf_token
}
template = render_to_string("bms/index.html", context)
response['template'] = template
response['status'] = True
return HttpResponse(json.dumps(response), content_type="applicaton/json")
return render(request, "bms/index.html", context)
My index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function update_entry(id) {
var id = id
$.ajax({
url: "{% url 'bms:index' %}",
type: "POST",
data:{
'csrfmiddlewaretoken': '{{ csrf_token }}',
'id' : id,
},
success: function(response){
$("#updateform").modal("show");
}
});
}
function update_property(id) {
window.location.replace("/bms/update" + id+"/");
}
</script>
<style>
body{
font-family: Raleway;
}
</style>
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Details of Books</h1>
</div>
<table class = "table table-bordered table-hover">
<tr>
<th>S No.:</th>
<th>Title:</th>
<th>Author:</th>
<th>Edition:</th>
<th>Publisher:</th>
<th>Genre:</th>
<th>Detail:</th>
<th>Language:</th>
<th>Price:</th>
<th>ISBN:</th>
<th>Action:</th>
</tr>
{% for item in book_detail %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.title }}</td>
<td>{{ item.author }}</td>
<td>{{ item.edition }}</td>
<td>{{ item.publisher }}</td>
<td>{{ item.genre }}</td>
<td>{{ item.detail }}</td>
<td>{{ item.language }}</td>
<td>{{ item.price }}</td>
<td>{{ item.isbn }}</td>
<td>
<a data-href="bms:update({{item.id}})" onclick="update_entry({{item.id}})" class="btn btn-warning" data-toggle="modal">
<span class = "glyphicon glyphicon-pencil"></span> Edit
</a>
</td>
</tr>
{% endfor %}
</table>
<div class="modal fade" id="updateform" role="dialog">
<div class="modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<b>Update Details</b>
</h3>
</div>
<div class = "modal-body">
<form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST">
{% csrf_token%}
<div class = "form-group">
<label for = "title">
Title:
</label>
<input class = "form-control" id="book_title" type = "text" name="title" value="{{ book.title }}">
</div>
<div class="form-group">
<label for = "author">
Author:
</label>
<input id="book_author" class = 'form-control' type = "text" name="author" value="{{ book.author }}">
</div>
<div class = "form-group">
<label for = "edition">
Edition:
</label>
<input id="book_edition" type = "text" class = 'form-control' name="edition" value="{{ book.edition }}">
</div>
<div class = "form-group">
<label for ="publisher">
Publisher:
</label>
<input id="book_publisher" type = "text" name="publisher" class = 'form-control' value="{{ book.publisher }}"/>
</div>
<div class = "form-group">
<label for ="genre">
Genre:
</label>
<input id="book_genre" type = "text" name="genre" class = 'form-control' value="{{ book.genre }}"/>
</div>
<div class = "form-group">
<label for ="language">
Language:
</label>
<input id="book_language" type = "text" name="language" class = 'form-control' value="{{ book.language }}"/>
</div>
<div class = "form-group">
<label for ="price">
Price:
</label>
<input id="book_price" type = "text" name="price" class = 'form-control' value="{{ book.price }}"/>
</div>
<div class = "form-group">
<label for ="isbn">
ISBN:
</label>
<input id="book_isbn" type = "text" name="isbn" class = 'form-control' value="{{ book.isbn }}"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Does the BookEntry model have a primary key column? I started having the same error when I added a primary key field on the model the id was referencing. Apparently the id column is replaced by the primary key field. I removed the key and migrated the changes.The error is gone now.

Django Ajax get request - load model instance into a form

I have a table in a HTML template that displays all instances of a django model. on each row of the template I have an edit button that looks up the primary key of each instance, and by clicking that button I want all the fields in the model instance to be populated in a modal by using ajax. After that I want to be able to edit the data and use ajax to send the edited data back to the database.
I have been searching all over the web and found this post that is exactly what I need, but I still can't get it to work. Any help would be greatly appreciated.
jQuery code
var modalDiv = $("#modal-div");
$(".open-modal").on("click", function() {
console.log("button clicked");
var url = $(this).attr('data-url').replace('/', '');
console.log("url:",url); // this returns my customer number but is not used in the code below
$.ajax({
url: $(this).attr("data-url"),
type: 'get',
success: function(data) {
console.log("success");
modalDiv.html(data);
$("#myEdit").modal(); //#myEdit is the ID of the modal
},
error : function() {
console.log("Error: this did not work"); // provide a bit more info about the error to the console
}
});
});
a tag in form
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
Needless to say, I keep receiving the error console.log message.
Below is the complete codebase.
Model:
class Kunde(models.Model):
avd = [('610','610'), ('615', '615'), ('620', '620'), ('625', '625'), '630', '630'), ('635', '635'),('640', '640'),('645', '645'), ('650', '650'), ('655', '655')]
avdeling = models.CharField(max_length=3, choices=avd)
selskap = models.CharField(max_length=50, unique=True)
kundenr = models.CharField('Kundenummer', max_length=15, unique=True, primary_key=True)
gatenavn = models.CharField(max_length=50,)
postnr = models.CharField('Postnummer', max_length=4)
poststed = models.CharField(max_length=30)
kommune = models.CharField(max_length=30)
timestamp = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
def get_absolute_url(self):
return reverse("dashboard:index")
def __str__(self):
return self.selskap
class Meta:
ordering = ['selskap']
Urls
app_name = "dashboard"
urlpatterns = [
path('', views.dashboard, name='index'),
path('', views.customer_list, name='customer_list'),
url(r'^(?P<kundenummer>[0-9]+)$', views.customer_update, name='customer_update'),
]
Views:
main view to display the table
def dashboard(request):
template = 'dashboard/index.html'
if request.user.groups.filter(name__in=['Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='630') | Q(avdeling='635')).all()
elif request.user.groups.filter(name__in=['Nord']).exists():
queryset = Kunde.objects.filter(Q(avdeling='610') | Q(avdeling='615') | Q(avdeling='620')).all()
elif request.user.groups.filter(name__in=['Øst']).exists():
queryset = Kunde.objects.filter(Q(avdeling='660') | Q(avdeling='655') | Q(avdeling='650')).all()
elif request.user.groups.filter(name__in=['Sør']).exists():
queryset = Kunde.objects.filter(Q(avdeling='640') | Q(avdeling='645')).all()
elif request.user.groups.filter(name__in=['Nord-Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='625')).all()
else:
queryset = Kunde.objects.all()
context = {
"object_list": queryset,
}
return render(request, template, context)
view to display the modal with
def customer_update(request, kundenr=None):
template = 'dashboard/index.html'
instance = get_object_or_404(Kunde, kundenr=kundenr)
context={
'selskap': instance.selskap,
'instance': instance,
}
return render(request, template, context)
HTML table
<div class"container-table" style="overflow-x:auto;">
<table class="display table table-bordered table-condensed" id="table_kundeliste">
<thead class="thead-inverse">
<tr>
<th>Avdeling</th>
<th>Selskap</th>
<th>Kundenr.</th>
<th>Poststed</th>
<th>Kommune</th>
<th>Rediger</th>
</tr>
</thead>
<tbody>
{% for kunde in object_list %}
<tr>
<td> {{ kunde.avdeling }} </td>
<td> {{ kunde.selskap }} </td>
<td> {{ kunde.kundenr }} </td>
<td> {{ kunde.poststed }} </td>
<td> {{ kunde.kommune }} </td>
<td>
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
this part include modal in html
<div id="modal-div" class="modal-div">
{% include 'dashboard/customer-modal.html' %}
</div>
this is the modal template itself
<div class="modal fade" id="myEdit" role="dialog">
<div class="modal-dialog">
<form class="well contact-form" method="post" action="{% url dashboard:'customer_update'}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label for="avdeling">Avdeling:</label>
<input type="text" class="form-control" required="" name="avdeling" value="{{ instance.avdeling }}" id="avdeling">
<label for="selskap">Selskap:</label>
<input type="text" class="form-control" required="" name="selskap" value="{{ instance.selskap }}" id="selskap">
<label for="kundenummer">Kundenummer:</label>
<input type="text" class="form-control" required="" name="kundenummer" value="{{ instance.kundenr }}" id="kundenummer">
<label for="gatenavn">Gatenavn:</label>
<input type="text" class="form-control" required="" name="gatenavn" value="{{ instance.gatenavn }}" id="gatenavn">
<label for="postnummer">Postnummer:</label>
<input type="text" class="form-control" required="" value="{{ instance.postnr }}" name="postnummer" id="postnummer" >
<label for="poststed">Poststed:</label>
<input type="text" class="form-control" required="" value="{{ instance.poststed }}" name="poststed" id="poststed" >
<label for="kommune">Kommune:</label>
<input type="text" class="form-control" required="" value="{{ instance.kommune }}" name="kommune" id="kommune" >
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Valider</button>
<button value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>

Categories