I'm pretty new to programming and i'm trying to write a program that will upload a file to a website. I really don't know what I'm doing wrong. The file isn't getting uploaded. I think my issue is to do with the multipart form data but i wouldn't be surprised if i'm wrong.
import requests, os, sys
url = "myURL"
uploadFile = {'ILWinterConditions.kmz': open('C:\\Users\\JOC-001\\Documents\\GIS\\IDOT\\ILWinterConditions.kmz', 'rb')}
payload = {
'fname': 'myfname',
'lname': 'mylname',
'org': 'myorg',
'phone': 'myphone',
'email': 'myemail',
'datadescrip': 'mydatadesc',
'uploadedfile': 'C:\\Users\\JOC-001\\Documents\\GIS\\IDOT\\ILWinterConditions.kmz'
}
r = requests.post(url, verify = False, auth=('myUsername','mypassword'), files=uploadFile, data=payload)
print r.content
Below is the response I'm getting from print and the file is not being uploaded
<head>
<title>*I have censored this*</title>
<link rel="stylesheet" href="styles.css"/>
</head>
<body>
<script type="text/javascript">
// Add other extensions here if we want to allow other files to be
// uploaded. Check is not case-sensitive. Will also be checked on
// the server.
var allowedExtensions = [ "kml", "kmz", "jpg", "png", "csv" ];
var maxSize = 12 * 1024*1024;
var errorMessage = "Only .csv, .kml, .kmz, .jpg, or .png files up to 12MB are accepted!";
// Checks that the file meets our criteria. This is just for user
// convenience-- to catch problems before they attempt to do the
// upload. The file will be checked again on the server too.
function FileIsOkay() {
var fileInput = document.getElementById('uploadedFile');
// First check the file's extension
var fileName = fileInput.value;
var fileExtension = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
var extensionOK = false;
for (var i=0; i<allowedExtensions.length; ++i) {
if (fileExtension == allowedExtensions[i].toLowerCase()) {
extensionOK = true;
break;
}
}
if (! extensionOK) {
alert(errorMessage);
return false;
}
// Now check the file's size.
// Doesn't work in IE, but that's okay... it'll get checked on
// the server any way.
if (fileInput.files) {
var file = fileInput.files[0];
if (file) {
if (file.size > maxSize) {
alert(errorMessage);
return false;
}
}
}
return true;
}
</script>
<div class="title">
<img src="webdavtitle.png"/>
</div>
<form method="POST" action="uploader.php" enctype="multipart/form-data" onsubmit="return FileIsOkay();" class="fileForm">
<table class="detailsTable">
<tr>
<td class="inputLabel">First Name:</td>
<td class="inputField"><input type="text" name="fname" size="40"></td>
</tr>
<tr>
<td class="inputLabel">Last Name:</td>
<td class="inputField"><input type="text" name="lname" size="40"></td>
</tr>
<tr>
<td class="inputLabel">Organization/Agency:</td>
<td class="inputField"><input type="text" name="org" size="40"></td>
</tr>
<tr>
<td class="inputLabel">Phone (DSN or Com):</td>
<td class="inputField"><input type="text" name="phone" size="40"></td>
</tr>
<tr>
<td class="inputLabel">Email:</td>
<td class="inputField"><input type="text" name="email" size="40"></td>
</tr>
<tr>
<td class="inputLabel">Data Description:</td>
<td class="inputField"><input type="text" name="datadescrip" size="40"></td>
</tr>
<tr>
<td class="inputLabel">
Choose a .kml, .kmz, .jpg,<br/>
or .png file to upload:
</td>
<td class="inputField">
<input id="uploadedFile" name="uploadedfile" size="40" type="file"/>
</td>
</tr>
<tr>
<td></td>
<td class="inputField"><input type="submit" value="Upload File"></input></td>
</tr>
</table>
</form>
<div class="footer">
<img border="0" src="horiz_grey_line.gif">
</div>
<div class="footer">
<img border="0" src="contacthelp.png">
</div>
<div class="footer">
<img border="0" src="nc_address.gif">
<img border="0" src="nc_webpolicy.gif">
</div>
</body>
I figured out the issue with this code. It should have been
uploadFile = {'uploadedfile': open('C:\\Users\\JOC-001\\Documents\\GIS\\IDOT\\ILWinterConditions.kmz', 'rb')}
to fit the form data. and 'payload' did not need the
'uploadedfile': 'C:\\Users\\JOC-001\\Documents\\GIS\\IDOT\\ILWinterConditions.kmz'
Related
I need help!
I have an ASP.NET Core 5 MVC Webapplication. I have a list with items from a .mdf-database and want a checkbox at the end of each item-row. When I am in the controller of this view, I want to have the ID of the item, which is checked. There could be more than one checked. But I don't know how to to this.
Below some snippets from my code:
Index.cshtml
<form asp-action="Send">
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Bez)
</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Bez)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
<td>
#Html.CheckBox("Finalized", false)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Send" class="btn btn-primary" />
<br /><br />
<p>Achtung! Beim Senden an einem Freitag wird der Dienstplan automatisch für den darauffolgenden Montag eingeteilt.</p>
</form>
Can someone help me? I just want the id's in a list in my controller, which are checked.
It seems you want to post the selected Ids to backend. Here is a working demo you could follow:
#Html.CheckBox("Finalized", false,new { #value=item.Id})
Controller:
[HttpPost]
//if the type of item.Id is int, it will receive int array in backend
public IActionResult Send(int[] Finalized)
{
//do your stuff...
}
I have the following code snippet and I'm looking for a better way to parse out the last name.
<TABLE BORDER="0" class="info" width="560">
<TR>
<TD VALIGN="top"> <B>First Name<B></FONT> </TD>
<TD VALIGN="top"> <INPUT TYPE="text" NAME="First_Name" SIZE="16" value="Ashley"> </TD>
<TD VALIGN="top"> <B>Last Name<B></FONT> </TD>
<TD VALIGN="top"> <INPUT TYPE="text" NAME="Last_Name" SIZE="16" value="Smith"> </TD>
</TR>
<tr>
<TD VALIGN="top" colspan="2"> <B>Company Name (if any):<B></FONT> </TD>
<TD VALIGN="top" colspan="2"> <INPUT TYPE="text" NAME="Company_Name" SIZE="24" value=""> </TD>
</tr>
<TR>
<TD VALIGN="top" colspan=2> <B>Address<B></FONT> </TD>
<TD VALIGN="top" colspan=2> <INPUT TYPE="text" NAME="Address" SIZE="24" value="123 Any Street Circle "> </TD>
</TR>
<tr>
<TD VALIGN="top" colspan=2> <B>City <B></FONT> <INPUT type="text" id="City" name="City" SIZE="14" value="Shady Town"> </TD>
<TD colspan="2" VALIGN="top"> <B>State<B></FONT> <INPUT type="text" id=State name=State SIZE="4" value="Tx"> <B>Zip<B></FONT> <INPUT type="text" id=Zip name=Zip SIZE="8
I have the following but I'm pretty sure I can do this without having to do the replace. What I'm trying to do below is find the starting point, finding the end point, and then taking the text in between. Then once I have that, remove the "matched" text leaving me with the value of the input field.
<cfset LastName_start = findNoCase('<INPUT TYPE="text" NAME="Last_Name" SIZE="16" value="', theString, 0)>
#lastName_start#
<cfset LastName_end = findNoCase('">', theString, 0)> #lastName_end#
<cfset lastNameValue = '#Mid(theString,LastName_start,LastName_end)#'>
#lastNameValue#
<cfset lastNameValue = replace(lastNameValue, '<INPUT TYPE="text" NAME="Last_Name" SIZE="16" value="', '')>
<cfset lastNameValue = replace(lastNameValue, '">', '')>
<cfset lastNameValue = listFirst(lastNameValue,'"')>
<cfdump var="#lastNameValue#" label="lastNameValue">
Any tips on how I can clean this up using ColdFusion? This is an ethical exercise.
And yes, I did try to format this.
I second Scott Stroz's suggestion about trying JSoup. It usually works well, and is very simple to use.
Download the JSoup jar and load it in your Application.cfc.
component {
this.name = "MyApplication";
this.javaSettings = { loadPaths = ["C:\path\to\jsoup-1.12.1.jar"] };
// ... more application settings
}
Create an instance of JSoup, parse the HTML string and use val() to grab the text of the first matching element. It returns an empty string if the element wasn't found.
You can find a bunch of other helpful examples in the JSoup Cookbook.
<cfscript>
yourHTMLString = '<TABLE BORDER="0" class="info" ......';
// parse html
jsoup = createObject("java", "org.jsoup.Jsoup");
root = jsoup.parse( yourHTMLString );
// get the first matching value ...
lastName = root.select("input[name='Last_Name']").val();
firstName = root.select("input[name='First_Name']").val();
companyName = root.select("input[name='Company_Name']").val();
cityName = root.select("input[name='City']").val();
stateName = root.select("input[name='State']").val();
address = root.select("input[name='Address']").val();
</cfscript>
Results:
I am making a complete admin and invoice app in Django.
For the invoice app, as the user clicks on "Create Sales Invoice" the invoice screen appears.
Now I want the system to dynamically generate new bill as soon as this screen appears, but not saved. As the user starts entering item, I want a new item detail (i.e. each bill has one item detail which has the list of items, its quantity and price).
However, none of them shall be saved unless the user clicks on create bill button.
I need help in how to do this thing, ie create a bill and item detail as the user goes to a create bill, link these two with foreign key, but also have the option to discard them if the user does not end up on clicking "save" button.
Edit 1
My invoicing HTML:
{% extends "base.html" %}
{% block title %}
{% load static from staticfiles %}
<script src="{% static 'bill/script.js' %}"></script>
<link rel="stylesheet" href="{% static 'bill/style.css' %}">
<title>Sales Invoice</title>
{% endblock %}
{% block content%}
<invoice>
<div id="invoice">
<invoiceheader>
<!--
<h1>Invoice</h1>
<address>
<p>Jonathan Neal</p>
<p>101 E. Chapman Ave<br>Orange, CA 92866</p>
<p>(800) 555-1234</p>
</address>
<span><img alt="" src="logo.png"><input type="file" accept="image/*"></span>
-->
</invoiceheader>
<invoicearticle>
<!--<h1>Recipient</h1>-->
<code>
<p>Customer code:
<input id="customer-code" ></input></p>
</code>
<address>
<p></p>
<p id="companyname">Some Company</p>
<p id = "companyaddress">c/o Some Guy</p>
</address>
<table class="meta">
<tr>
<th><span>Invoice #</span></th>
<td><span>101138</span></td>
</tr>
<tr>
<th><span>Date</span></th>
<td><span></span></td>
</tr>
<tr>
<th><span>Amount Due</span></th>
<td><span id="prefix">Rs. </span><span>600.00</span></td>
</tr>
</table>
<table class="inventory" id="inventory_table">
<thead>
<tr>
<th colspan="1"><span>Item Code</span></th>
<th colspan="2"><span>Item Name</span></th>
<th colspan="1"><span>Unit Rate</span></th>
<th colspan="1"><span>Discount 1</span></th>
<th colspan="1"><span>Quantity</span></th>
<th colspan="1"><span>Discount 2</span></th>
<th colspan="1"><span>Free Quantity</span></th>
<th colspan="1"><span>VAT Type</span></th>
<th colspan="1"><span>VAT</span></th>
<th colspan="1"><span>Net Rate</span></th>
</tr>
</thead>
<form>
<tbody>
<tr>
<td colspan="1"><a class="cut">-</a><span class="itemcode" contenteditable></span></td>
<td colspan="2"><span contenteditable></span></td>
<td colspan="1"><span contenteditable>150.00</span></td>
<td colspan="1"><span contenteditable></span></td>
<td colspan="1"><span contenteditable>4</span></td>
<td colspan="1"><span contenteditable></span></td>
<td colspan="1"><span contenteditable></span></td>
<td colspan="1"><span contenteditable></span></td>
<td colspan="1"><span contenteditable></span></td>
<td colspan="1"><span contenteditable></span></td>
</tr>
</tbody>
</form>
</table>
<a class="add">+</a>
<table class="balance">
<tr>
<th><span>Total</span></th>
<td><span data-prefix></span><span>600.00</span></td>
</tr>
<tr>
<th><span>Amount Paid</span></th>
<td><span data-prefix></span><span>0.00</span></td>
</tr>
<tr>
<th><span>Balance Due</span></th>
<td><span data-prefix></span><span>600.00</span></td>
</tr>
</table>
</article>
</div>
</invoice>
<script type="text/javascript">
/* url_sellbill = '{% url "billbrain:sellbill" %}' */
csrf_token='{{csrf_token}}'
</script>
{% endblock %}
My related jquery file (only the necessary part):
Generating Table:
function generateTableRow() {
var emptyColumn = document.createElement('tr');
emptyColumn.innerHTML = '<td><a class="cut">-</a><span class="itemcode" contenteditable></span></td>' +
'<td colspan="2"><span contenteditable></span></td>' +
'<td><span contenteditable>100.00</span></td>' +
'<td><span contenteditable></span></td>' +
'<td><span contenteditable></span></td>'+
'<td><span contenteditable></span></td>' +
'<td><span contenteditable></span></td>'+
'<td><span contenteditable></span></td>' +
'<td><span contenteditable></span></td>' +
'<td><span contenteditable></span></td>' ;
return emptyColumn;
}
Adding customer details on user entering customer code:
$( "#customer-code" ).change(function() {
/*alert( "Handler for .change() called." );*/
var input = $("#customer-code").val();
(function() {
$.ajax({
url : "",
type : "POST",
data : { customer_code: input,
datatype: 'customer',
'csrfmiddlewaretoken': csrf_token}, // data sent with the post request
dataType: 'json',
// handle a successful response
success : function(jsondata) {
$('#companyname').html(jsondata['name'])
$('#companyaddress').html(jsondata['address'])
console.log(jsondata); // log the returned json to the console
console.log("success"); // another sanity check
},
});
}());
});
Similarly, for products, on user entering product id, the other details are auto-generated:
$("#inventory_table").on("focus", ".itemcode", function(){
$(this).data("initialText", $(this).html());
/*alert( "On focus for table inventory called." );*/
});
$("#inventory_table").on("blur", ".itemcode", function(){
/*alert( "On blur for table inventory called." );*/
var input = $(this).html();
if ($(this).data("initialText") !== $(this).html()) {
var el = this;
/*valueis='Hi 5'
alert($(this).closest('tr').find('td:nth-child(4) span').html());*/
(function() {
$.ajax({
url : "",
type : "POST",
data : { item_code: input,
datatype: 'item',
'csrfmiddlewaretoken': csrf_token}, // data sent with the post request
dataType: 'json',
// handle a successful response
success : function(jsondata) {
$(el).closest('tr').find('td:nth-child(2) span').html(jsondata['name'])
$(el).closest('tr').find('td:nth-child(2) span').html(jsondata['name'])
$(el).closest('tr').find('td:nth-child(3) span').html(jsondata['sellingprice'])
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
console.log("success"); // another sanity check
},
});
}());
}
});
Finally, this is my views.py file's relevant function:
def bill(request):
if request.method == 'POST':
datatype = request.POST.get('datatype')
if (datatype == 'customer'):
customerkey = request.POST.get('customer_code')
response_data = {}
response_data['name'] = Customer.object.get(customer_key__iexact=customerkey).name
response_data['address'] = Customer.object.get(customer_key__iexact=customerkey).address
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
if (datatype == 'item'):
productkey = request.POST.get('item_code')
response_data = {}
response_data['name'] = Product.object.get(prodkey__iexact=productkey).name
response_data['sellingprice'] = float(Product.object.get(prodkey__iexact=productkey).selling_price)
#response_data['address'] = Product.object.get(prodkey__iexact=productkey).address
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
return render(request, 'bill/invoicing.html')
You should use Model Forms to output to the user a form to fill and create an object after submit. You can also use some context data if you need to pre-fill some informations in the form.
Another way is to just create an object and flag it as "CANCELLED" if you want to remember some user's tries (what can be useful sometimes) or just remove it (what can cause performance issues if it is very common situation to not fill started bill).
I have the following HTML:
<div>
<table>
<tr>
<td>
<div class="w135">
<div style="float: left; padding-right: 10px;" class="imageThumbnail playerDiv">
<a href="/sport/tennis/2014/10/djokovic-through-wozniacki-out-china-open-2014101114115427766.html" id="ctl00_ctl00_DataList1_ctl00_Thumbnail1_lnkImage10" target="_parent">
<img src="/mritems/imagecache/89/135/mritems/images/2014/10/1/2014101114447491734_20.jpg" id="ctl00_ctl00_DataList1_ctl00_Thumbnail1_imgSmall10" border="0" class="imageThumbnail">
</a>
</div>
</div>
</td>
</tr>
</table>
</div>
When i attempt the rake, i get the error:
NoMethodError: undefined method `at_css' for ["id","ctl00_cphBody_ctl01_DataList1_ctl00_Thumbnail1_Layout17"]:Array
This is the code:
#request = HTTParty.get(url)
#html = Nokogiri::HTML(#request.body)
#html.css(".w135")[0].map do |item|
url = item.at_css("div.playerDiv a")
puts url.inspect
end
I'm really not sure what the issue is and have been trying to fix this for a while. The error occurs on this line url = item.at_css("div.playerDiv a")
Any suggestion is appreciated!
Thanks
I'd do it using something like:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<div>
<table>
<tr>
<td>
<div class="w135">
<div style="float: left; padding-right: 10px;" class="imageThumbnail playerDiv">
<a href="/sport/tennis/2014/10/djokovic-through-wozniacki-out-china-open-2014101114115427766.html" id="ctl00_ctl00_DataList1_ctl00_Thumbnail1_lnkImage10" target="_parent">
<img src="/mritems/imagecache/89/135/mritems/images/2014/10/1/2014101114447491734_20.jpg" id="ctl00_ctl00_DataList1_ctl00_Thumbnail1_imgSmall10" border="0" class="imageThumbnail">
</a>
</div>
</div>
</td>
</tr>
</table>
</div>
EOT
puts doc.search('.w135 div.playerDiv a').map(&:inspect)
Which outputs:
# >> #<Nokogiri::XML::Element:0x3ff0918b132c name="a" attributes=[#<Nokogiri::XML::Attr:0x3ff0918b1250 name="href" value="/sport/tennis/2014/10/djokovic-through-wozniacki-out-china-open-2014101114115427766.html">, #<Nokogiri::XML::Attr:0x3ff0918b123c name="id" value="ctl00_ctl00_DataList1_ctl00_Thumbnail1_lnkImage10">, #<Nokogiri::XML::Attr:0x3ff0918b1228 name="target" value="_parent">] children=[#<Nokogiri::XML::Text:0x3ff0918a5b6c "\n ">, #<Nokogiri::XML::Element:0x3ff0918a5360 name="img" attributes=[#<Nokogiri::XML::Attr:0x3ff0918a4d20 name="src" value="/mritems/imagecache/89/135/mritems/images/2014/10/1/2014101114447491734_20.jpg">, #<Nokogiri::XML::Attr:0x3ff0918a4cbc name="id" value="ctl00_ctl00_DataList1_ctl00_Thumbnail1_imgSmall10">, #<Nokogiri::XML::Attr:0x3ff0918a4b90 name="border" value="0">, #<Nokogiri::XML::Attr:0x3ff0918a4a28 name="class" value="imageThumbnail">]>, #<Nokogiri::XML::Text:0x3ff091871920 "\n ">]>
If you're trying to access the "href" parameter, instead of using inspect, use:
puts doc.search('.w135 div.playerDiv a').map{ |n| n['href'] }
# >> /sport/tennis/2014/10/djokovic-through-wozniacki-out-china-open-2014101114115427766.html
In my code repeater is nested in datalistdatalist contains checkboxes and radiobutton
i want to do database operation on checkchanged of checkboxes,so i had written this operation on repeater itemcomand. Here I am not able to find control of repeater.so please guide me how to find control of repeater.
My design is like this:
<asp:DataList ID="DatalistQues" runat="server" DataKeyField="QuestionID" OnSelectedIndexChanged="DataListText_SelectedIndexChanged"
Width="100%" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<table width="100%">
<tr>
<td style="width: 13%">
<asp:LinkButton ID="LinkButton6" runat="server" CommandName="Select" CssClass="ppppp">
<asp:Image ID="Image1" runat="server" ImageUrl='<% #Eval("Image")%>' Height="60px"
Width="65px" />
</asp:LinkButton>
</td>
<td style="width: 87%">
<asp:LinkButton ID="LinkButton7" runat="server" CommandName="Select" CssClass="ppppp">
<asp:Label ID="Label3" runat="server" Text='<% #Eval("name")%>'></asp:Label>
</asp:LinkButton>
</td>
</tr>
<tr>
<td style="width: 13%">
</td>
<td style="width: 87%; white-space: pre-line">
<asp:Label ID="TextBox2" runat="server" Text='<% #Eval("Question")%>'></asp:Label>
</td>
</tr>
<tr>
<td style="width: 13%">
</td>
<td style="width: 87%">
<script type="text/javascript" language="javascript">
function fnCheckUnCheck(objId) {
var grd = document.getElementById("TabContainer1_TabPanel2_DatalistQues");
alert(grd);
//Collect A
var rdoArray = grd.getElementsByTagName("input");
alert(rdoArray);
for (i = 0; i <= rdoArray.length - 1; i++) {
if (rdoArray[i].type == 'radio') {
if (rdoArray[i].id != objId) {
rdoArray[i].checked = false;
}
}
}
}
</script>
<asp:Repeater ID="RepeaterQues" runat="server" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table style="border: none">
<tr>
<td style="width: 100px">
<asp:LinkButton ID="LinkButton23" runat="server" CommandName="radiob">
<asp:RadioButton ID="RadioButton1" runat="server" onclick="fnCheckUnCheck(this.id);" /></asp:LinkButton><asp:LinkButton
ID="LinkButton24" runat="server" CommandName="checkb">
<asp:CheckBox ID="CheckBox1" runat="server" Text='<%#Eval("QOption") %>' /></asp:LinkButton>
</td>
<td style="width: 100px">
<asp:Label ID="empname" Text='<%#Eval("QOption") %>' runat="server"></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Try this
((Repeater)e.Item.Parent).ID // this gives the ID as specified on the aspx page
If you need Unique ID, you have to use this
((Repeater)e.Item.Parent).ClientID
On Item command of Repeater you will have to first find the naming container of sender
it will return you datalist item.
then in returned list item you will have to find the repeater of that particular data list itme
once you will find the repeater you can easily find the controls of the item of repeater