Search Results

Search found 27 results on 2 pages for 'fileinput'.

Page 1/2 | 1 2  | Next Page >

  • Use Regular expression with fileinput

    - by chrissygormley
    Hello, I am trying to replace a variable stored in another file using regular expression. The code I have tried is: r = re.compile(r"self\.uid\s*=\s*('\w{12})'") for line in fileinput.input(['file.py'], inplace=True): print line.replace(r.match(line), sys.argv[1]), The format of the variable in the file is: self.uid = '027FC8EBC2D1' I am trying to pass in a parameter in this format and use regular expression to verify that the sys.argv[1] is correct format and to find the variable stored in this file and replace it with the new variable. Can anyone help. Thanks for the help.

    Read the article

  • FileInput Help/Advice

    - by user559142
    I have a fileinput class. It has a string parameter in the constructor to load the filename supplied. However it just exits if the file doesn't exist. I would like it to output a message if the file doesn't exist - but not sure how.... Here is the class: public class FileInput extends Input { /** * Construct <code>FileInput</code> object given a file name. */ public FileInput(final String fileName) { try { scanner = new Scanner(new FileInputStream(fileName)); } catch (FileNotFoundException e) { System.err.println("File " + fileName + " could not be found."); System.exit(1); } } /** * Construct <code>FileInput</code> object given a file name. */ public FileInput(final FileInputStream fileStream) { super(fileStream); } } And its implementation: private void loadFamilyTree() { out.print("Enter file name: "); String fileName = in.nextLine(); FileInput input = new FileInput(fileName); family.load(input); input.close(); }

    Read the article

  • Get dimensions for dataset matlab, Size Function

    - by Tim
    Hello I have been trying to display the dimensions of a dataset, below is the following matlab code that i used...but it gives me the wrong output....i'e number of rows and columns values are wrong....any help regarding this issue would be highly appreciated [file_input,pathname] = uigetfile( ... {'*.txt', 'Text (*.txt)'; ... '*.xls', 'Excel (*.xls)'; ... '*.*', 'All Files (*.*)'}, ... 'Select files'); [pathstr, name, ext, versn] = fileparts(file_input) r = size(name,1); c = size(name,2); disp(r) disp(c)

    Read the article

  • How to store multiple variables from a File Input of unknown size in Java?

    - by AlphaOmegaStrife
    I'm a total beginner with my first programming assignment in Java. For our programming assignment, we will be given a .txt file of students like so: 3 345 Lisa Miller 890238 Y 2 <-(Number of classes) Mathematics MTH345 4 A Physics PHY357 3 B Bill Wilton 798324 N 2 English ENG378 3 B Philosophy PHL534 3 A Dandy Goat 746333 Y 1 History HIS101 3 A" The teacher will give us a .txt file on the day of turning it in with a list of unknown students. My problem is: I have a specific class for turning the data from the file into variables to be used for a different class in printing it to the screen. However, I do not know of a good way to get the variables from the input file for the course numbers, since that number is not predetermined. The only way I can think of to iterate over that unknown amount is using a loop, but that would just overwrite my variables every time. Also, the teacher has requested that we not use any JCL classes (I don't really know what this means.) Sorry if I have done a poor job of explaining this, but I can't think of a better way to conceptualize it. Let me know if I can clarify. Edit: public static void analyzeData() { Scanner inputStream = null; try { inputStream = new Scanner(new FileInputStream("Programming Assignment 1 Data.txt")); } catch (FileNotFoundException e) { System.out.println("File Programming Assignment 1 Data.txt could not be found or opened."); System.exit(0); } int numberOfStudents = inputStream.nextInt(); int tuitionPerHour = inputStream.nextInt(); String firstName = inputStream.next(); String lastname = inputStream.next(); String isTuitionPaid = inputStream.next(); int numberOfCourses = inputStream.nextInt(); String courseName = inputStream.next(); String courseNumber = inputStream.next(); int creditHours = inputStream.nextInt(); String grade = inputStream.next(); To show the methods I am using now, I am just using a Scanner to read from the file and for Scanner inputStream, I am using nextInt() or next() to get variables from the file. Obviously this will not work when I do not know exactly how many classes each student will have.

    Read the article

  • Replace text in file with Python

    - by Aaron Hoffman
    I'm trying to replace some text in a file with a value. Everything works fine but when I look at the file after its completed there is a new (blank) line after each line in the file. Is there something I can do to prevent this from happening. Here is the code as I have it: import fileinput for line in fileinput.FileInput("testfile.txt",inplace=1): line = line.replace("newhost",host) print line Thank you, Aaron

    Read the article

  • Javascript upload in spite of same origin policy

    - by Brian M. Hunt
    Can one upload files to a domain other than the domain a script originates from? For example, suppose you're hosting files on www.example.com, and you want to upload files to uploads.example.com, would the following script violate the same origin policy (using uploadify): <!-- from http://www.example.com/upload.html --> <input id="fileInput" name="fileInput" type="file" /> <script type="text/javascript">// <![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : 'uploadify.swf', 'script' : 'http://upload.example.com/uploadify.php', 'cancelImg' : 'cancel.png', 'auto' : true, 'folder' : '/uploads' }); }); // ]]></script> I haven't seen a clear reference on the same origin policy that would indicate one-way or the other whether the this would be an issue with any browsers.

    Read the article

  • jQuery Validation Engine with Mime

    - by Diego Pucci
    I have this custom rule with tje jQuery validation Engine: "validateMIME": { "func": function(field, rules, i, options){ var fileInput = field[0].files[0]; var MimeFilter = new RegExp(rules[3],'i'); if (fileInput) { return MimeFilter.test(fileInput.type); } else { return true;} }, "alertText": "* Estensione non supportata" }, The problem is that this is working ONLY if the field is required. But in my case the field is not required, but if filled then the Mime type needs to be checked. How do I edit this function to work with non required fields? what's wrong with it? Thanks

    Read the article

  • Find&Replace using Python - Binary file

    - by Aaron Hoffman
    Hello, I'm attempting to do a "find and replace" in a file on a Mac OS X computer. Although it appears to work correctly. It seems that the file is somehow altered. The text editor that I use (Text Wrangler) is unable to even open the file once this is completed. Here is the code as I have it: import fileinput for line in fileinput.FileInput("testfile.txt",inplace=1): line = line.replace("newhost",host) print line, When I view the file from the terminal, it does say "testfile" may be a binary file. See it anyway? Is there a chance that this replace is corrupting the file? Do I have another option for this to work? I really appreciate the help. Thank you, Aaron UPDATE: the actual file is NOT a .txt file it is a .plist file which is preference file in Mac OS X if that makes any difference

    Read the article

  • django+uploadify - don't working

    - by Erico
    Hi, I'm trying to use an example posted on the "github" the link is http://github.com/tstone/django-uploadify. And I'm having trouble getting work. can you help me? I followed step by step, but does not work. Accessing the "URL" / upload / the only thing is that returns "True" part of settings.py import os PROJECT_ROOT_PATH = os.path.dirname(os.path.abspath(file)) MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, 'media') TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT_PATH, 'templates')) urls.py from django.conf.urls.defaults import * from django.conf import settings from teste.uploadify.views import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), url(r'upload/$', upload, name='uploadify_upload'), ) views.py from django.http import HttpResponse import django.dispatch upload_received = django.dispatch.Signal(providing_args=['data']) def upload(request, *args, **kwargs): if request.method == 'POST': if request.FILES: upload_received.send(sender='uploadify', data=request.FILES['Filedata']) return HttpResponse('True') models.py from django.db import models def upload_received_handler(sender, data, **kwargs): if file: new_media = Media.objects.create( file = data, new_upload = True, ) new_media.save() upload_received.connect(upload_received_handler, dispatch_uid='uploadify.media.upload_received') class Media(models.Model): file = models.FileField(upload_to='images/upload/', null=True, blank=True) new_upload = models.BooleanField() uploadify_tags.py from django import template from teste import settings register = template.Library() @register.inclusion_tag('uploadify/multi_file_upload.html', takes_context=True) def multi_file_upload(context, upload_complete_url): """ * filesUploaded - The total number of files uploaded * errors - The total number of errors while uploading * allBytesLoaded - The total number of bytes uploaded * speed - The average speed of all uploaded files """ return { 'upload_complete_url' : upload_complete_url, 'uploadify_path' : settings.UPLOADIFY_PATH, # checar essa linha 'upload_path' : settings.UPLOADIFY_UPLOAD_PATH, } template - uploadify/multi_file_upload.html {% load uploadify_tags }{ multi_file_upload '/media/images/upload/' %} <script type="text/javascript" src="{{ MEDIA_URL }}js/swfobject.js"></script> <script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.uploadify.js"></script> <div id="uploadify" class="multi-file-upload"><input id="fileInput" name="fileInput" type="file" /></div> <script type="text/javascript">// <![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : '/media/swf/uploadify.swf', 'script' : '{% url uploadify_upload %}', 'cancelImg' : '/media/images/uploadify-remove.png/', 'auto' : true, 'folder' : '/media/images/upload/', 'multi' : true, 'onAllComplete' : allComplete }); }); function allComplete(event, data) { $('#uploadify').load('{{ upload_complete_url }}', { 'filesUploaded' : data.filesUploaded, 'errorCount' : data.errors, 'allBytesLoaded' : data.allBytesLoaded, 'speed' : data.speed }); // raise custom event $('#uploadify') .trigger('allUploadsComplete', data); } // ]]</script>

    Read the article

  • Uploadify not working with ASP.NET WebForms

    - by João Guilherme
    Hi ! I'm trying to use Uploadify in a ASP.NET webforms project. The problem is that my script is not calling the generic handler. Here is the script. <input id="fileInput" name="fileInput" type="file" /> <script type="text/javascript"> $(document).ready(function() { $('#fileInput').uploadify({ 'uploader': '/Ferramenta/Comum/Uploadify/uploadify.swf', 'script': 'UploadTest.ashx', 'cancelImg': '/Ferramenta/Comum/Uploadify/cancel.png', 'folder': "/Ferramenta/Geral/", 'auto': true, 'onError': function(event, queueID, fileObj, errorObj) { alert('error'); }, 'onComplete': function(event, queueID, fileObj, response, data) { alert('complete'); }, 'buttonText' : 'Buscar Arquivos' }); }); </script> This is the code of the generic handler (just to test) using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.IO; namespace Tree.Ferramenta.Geral { public class UploadTest : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.Write("1"); } public bool IsReusable { get { return false; } } } } Any ideas ? Thanks !

    Read the article

  • Python and csv help

    - by user353064
    I'm trying to create this script that will check the computer host name then search a master list for the value to return a corresponding value in the csv file. Then open another file and do a find an replace. I know this should be easy but haven't done so much in python before. Here is what I have so far... masterlist.txt (tab delimited) Name UID Bob-Smith.local bobs Carmen-Jackson.local carmenj David-Kathman.local davidk Jenn-Roberts.local jennr Here is the script that I have created thus far #GET CLIENT HOST NAME import socket host = socket.gethostname() print host #IMPORT MASTER DATA import csv, sys filename = "masterlist.txt" reader = csv.reader(open(filename, "rU")) #PRINT MASTER DATA for row in reader: print row #SEARCH ON HOSTNAME AND RETURN UID #REPLACE VALUE IN FILE WITH UID #import fileinput #for line in fileinput.FileInput("filetoreplace",inplace=1): # line = line.replace("replacethistext","UID") # print line Right now, it's just set to print the master list. I'm not sure if the list needs to be parsed and placed into a dictionary or what. I really need to figure out how to search the first field for the hostname and then return the field in the second column. Thanks in advance for your help, Aaron

    Read the article

  • Referencing java resource files for cold fusion

    - by Chimeara
    I am using a .Jar file containing a .properties file in my CF code, however it seems unable to find the .properties file when run from CF. My java code is: String key =""; String value =""; try { File file = new File("src/test.properties"); FileInputStream fileInput = new FileInputStream(file); Properties properties = new Properties(); properties.load(fileInput); fileInput.close(); Enumeration enuKeys = properties.keys(); while (enuKeys.hasMoreElements()) { key = (String) enuKeys.nextElement(); value = properties.getProperty(key); //System.out.println(key + ": " + value); } } catch (FileNotFoundException e) { e.printStackTrace(); key ="error"; } catch (IOException e) { e.printStackTrace(); key ="error"; } return(key + ": " + value); I have my test.properties file in the project src folder, and make sure it is selected when compiling, when run from eclipse it gives the expected key and value, however when run from CF I get the caught errors. My CF code is simply: propTest = CreateObject("java","package.class"); testResults = propTest.main2(); Is there a special way to reference the .properties file so CF can access it, or do I need to include the file outside the .jar somewhere?

    Read the article

  • GZipStream not reading the whole file

    - by Ed
    I have some code that downloads gzipped files, and decompresses them. The problem is, I can't get it to decompress the whole file, it only reads the first 4096 bytes and then about 500 more. Byte[] buffer = new Byte[4096]; int count = 0; FileStream fileInput = new FileStream("input.gzip", FileMode.Open, FileAccess.Read, FileShare.Read); FileStream fileOutput = new FileStream("output.dat", FileMode.Create, FileAccess.Write, FileShare.None); GZipStream gzipStream = new GZipStream(fileInput, CompressionMode.Decompress, true); // Read from gzip steam while ((count = gzipStream.Read(buffer, 0, buffer.Length)) > 0) { // Write to output file fileOutput.Write(buffer, 0, count); } // Close the streams ... I've checked the downloaded file; it's 13MB when compressed, and contains one XML file. I've manually decompressed the XML file, and the content is all there. But when I do it with this code, it only outputs the very beginning of the XML file. Anyone have any ideas why this might be happening?

    Read the article

  • Python 2.5.2: trying to open files recursively

    - by user248959
    Hi, the script below should open all the files inside the folder 'pruebaba' recursively but i get this error: Traceback (most recent call last): File "/home/tirengarfio/Desktop/prueba.py", line 8, in f = open(file,'r') IOError: [Errno 21] Is a directory This is the hierarchy: pruebaba folder1 folder11 test1.php folder12 test1.php test2.php folder2 test1.php The script: import re,fileinput,os path="/home/tirengarfio/Desktop/pruebaba" os.chdir(path) for file in os.listdir("."): f = open(file,'r') data = f.read() data = re.sub(r'(\s*function\s+.*\s*{\s*)', r'\1echo "The function starts here."', data) f.close() f = open(file, 'w') f.write(data) f.close() Any idea? Regards Javi

    Read the article

  • asp:FileUpload not working in UpdatePanel

    - by James123
    asp:FileUpload control is not working in update panel in ascx control. Why? any work around. <span dir="ltr"> <asp:FileUpload ID="InputFile" runat="server" class="ms-fileinput" size="35" /> </span> and also I added <Triggers> <asp:PostBackTrigger ControlID="btnOK" /> </Triggers> Still it is not working.

    Read the article

  • Jquery Hide table rows

    - by tomasz
    Hi there I am hiding a bunch of textboxes and it works fine, the problem is, the textboxes are in a table, so I also need to hide the corresponding labels. the structure is something like this <tr> <td> Label </td> <td> InputFile </td> </tr> in fact its just easier if I hide the rows that have a fileinput , can someone help please

    Read the article

  • Sleeping a thread blocking stdin

    - by Sid
    Hey, I'm running a function which evaluates commands passed in using stdin and another function which runs a bunch of jobs. I need to make the latter function sleep at regular intervals but that seems to be blocking the stdin. Any advice on how to resolve this would be appreciated. The source code for the functions is def runJobs(comps, jobQueue, numRunning, limit, lock): while len(jobQueue) >= 0: print(len(jobQueue)); if len(jobQueue) > 0: comp, tasks = find_computer(comps, 0); #do something time.sleep(5); def manageStdin(): print "Global Stdin Begins Now" for line in fileinput.input(): try: print(eval(line)); except Exception, e: print e; --Thanks

    Read the article

  • Customizing Django form widgets? - Django

    - by RadiantHex
    Hi folks, I'm having a little problem here! I have discovered the following as being the globally accepted method for customizing Django admin field. from django import forms from django.utils.safestring import mark_safe class AdminImageWidget(forms.FileInput): """ A ImageField Widget for admin that shows a thumbnail. """ def __init__(self, attrs={}): super(AdminImageWidget, self).__init__(attrs) def render(self, name, value, attrs=None): output = [] if value and hasattr(value, "url"): output.append(('<a target="_blank" href="%s">' '<img src="%s" style="height: 28px;" /></a> ' % (value.url, value.url))) output.append(super(AdminImageWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) I need to have access to other field of the model in order to decide how to display the field! For example: If I am keeping track of a value, let us call it "sales". If I wish to customize how sales is displayed depending on another field, let us call it "conversion rate". I have no obvious way of accessing the conversion rate field when overriding the sales widget! Any ideas to work around this would be highly appreciated! Thanks :)

    Read the article

  • Uploadify - Passing Information Back to The Original Form

    - by CccTrash
    I have an Send.aspx page that has an uploadify control on it. Upload.ashx handles the file upload. I am adding a file record to a sql database in the Upload.ashx file and I need to get the ID of that record back from Upload.aspx when it is done. Can't get it working with Sessions. =( Something to do with an Adobe bug? What would the best way to handle this be? Here is the uploadify control: <script type="text/javascript"> // <![CDATA[ var contestID = $('[id$=HiddenFieldContestID]').val(); var maxEntries = $('[id$=HiddenFieldMaxEntries]').val(); var userID = $('[id$=HiddenFieldUserID]').val(); $(document).ready(function() { $('#fileInput').uploadify({ 'uploader': '../uploadify/uploadify.swf', 'script': '../uploadify/Upload.ashx', 'scriptData': { 'contestID': contestID, 'maxEntries': maxEntries, 'userID': userID }, 'cancelImg': '../uploadify/cancel.png', 'auto': true, 'multi': false, 'fileDesc': 'Image Files', 'fileExt': '*.jpg;*.png;*.jpeg', 'queueSizeLimit': 1, 'sizeLimit': 4000000, 'buttonText': 'Choose Image', 'folder': '/uploads', 'onAllComplete': function(event, queueID, fileObj, response, data) { document.getElementById('<%= ButtonCleanup.ClientID %>').click(); } }); }); // ]]></script> Edit: See Answer below... Video Tutorial from start to finish: http://casonclagg.com/articles/6/video-tutorial-uploadify-asp-net-c-sharp.aspx

    Read the article

  • Django Upload form to S3 img and form validation

    - by citadelgrad
    I'm fairly new to both Django and Python. This is my first time using forms and upload files with django. I can get the uploads and saves to the database to work fine but it fails to valid email or check if the users selected a file to upload. I've spent a lot of time reading documentation trying to figure this out. Thanks! views.py def submit_photo(request): if request.method == 'POST': def store_in_s3(filename, content): conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(AWS_STORAGE_BUCKET_NAME) mime = mimetypes.guess_type(filename)[0] k = Key(bucket) k.key = filename k.set_metadata("Content-Type", mime) k.set_contents_from_file(content) k.set_acl('public-read') if imghdr.what(request.FILES['image_url']): qw = request.FILES['image_url'] filename = qw.name image = filename content = qw.file url = "http://bpd-public.s3.amazonaws.com/" + image data = {image_url : url, user_email : request.POST['user_email'], user_twittername : request.POST['user_twittername'], user_website : request.POST['user_website'], user_desc : request.POST['user_desc']} s = BeerPhotos(data) if s.is_valid(): #import pdb; pdb.set_trace() s.save() store_in_s3(filename, content) return HttpResponseRedirect(reverse('photos.views.thanks')) return s.errors else: return errors else: form = BeerPhotoForm() return render_to_response('photos/submit_photos.html', locals(),context_instance=RequestContext(request) forms.py class BeerPhotoForm(forms.Form): image_url = forms.ImageField(widget=forms.FileInput, required=True,label='Beer',help_text='Select a image of no more than 2MB.') user_email = forms.EmailField(required=True,help_text='Please type a valid e-mail address.') user_twittername = forms.CharField() user_website = forms.URLField(max_length=128,) user_desc = forms.CharField(required=True,widget=forms.Textarea,label='Description',) template.html <div id="stylized" class="myform"> <form action="." method="post" enctype="multipart/form-data" width="450px"> <h1>Photo Submission</h1> {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} <label><span>Click here</span></label> <input type="submit" class="greenbutton" value="Submit your Photo" /> </form> </div>

    Read the article

  • Cloning input type file and set the value

    - by jribeiro
    I know that it isn't possible to set the value of an input type="file" for security reasons... My problem is: I needed to style an input type="file" so what I did was have a button and hide the file input. like: <a href="#" onclick="$('input[name=&quot;photo1&quot;]').click(); return false;" id="photo1-link"></a> <input type="file" name="photo1" class="fileInput jqtranformdone validate[required]" id="photo1" /> These works great in all browsers except IE which gives me an access denied error on submitting through ajax. I'm using the ajaxSubmit jquery plugin (malsup.com/jquery/form/) So after reading for a while I tried to do: var photo1Val = $('#photo1').val(); var clone1 = $('#photo1').clone().val(photo1Val); $('#photo1').remove(); clone1.appendTo('form'); console.log(photo1Val) //prints the right value C:/fakepath/blablabla.jpg $('form').ajaxSubmit(options); The problem is that after this the value of $('#photo1') is empty... Any ideas how to work around this? Thanks

    Read the article

  • Java Input/Output streams for unnamed pipes created in native code?

    - by finrod
    Is there a way to easily create Java Input/Output streams for unnamed pipes created in native code? Motivation: I need my own implementation of the Process class. The native code spawns me a new process with subprocess' IO streams redirected to unnamed pipes. Problem: The file descriptors for correct ends of those pipes make their way to Java. At this point I get stuck as I cannot create a new FileDescriptor which I could pass to FileInput/FileOutput stream. I have used reflection to get around the problem and got communication with a simple bouncer sub-process running. However I have a notion that it is not the cleanest way to go. Have you used this approach? Do you see any problems with this approach? (the platform will never change) Searching around the internets revealed similar solution using native code. Any thoughts before I dive into heavy testing of this approach are very welcome. I would like to give a shot to existing code before writing my own IO stream implementations... Thank you.

    Read the article

  • HTML input not working correctly with AJAX update panels used else where on page

    - by Sean P
    I have some update panels on my page that do some asyncpostbacks to keep some dropdownlists correctly populated. My problem is that on my page i have an HTML input that is handling some file uploads. With the AJAX on the page with asyncpostbacks, and while i step through my code behind, the files arent being uploaded. Using a postbacktrigger (non-async) is not possible because of my layout. Here is my code: <div id="divFileInputs" runat="server"> <input id="file1" name="fileInput" type="file" runat="server" size="50" style="width: 50em" onfocus="AddFileInput()" class="textbox" /></div> <select id="selectFileList" name="ListBox1" size="5" style="width: 50em; text-align: left;" class="textbox" /> <input id="RemoveAttachmentButton" type="button" value="Remove" onclick="RemoveFileInput()" class="removebutton " /> </div> Here is my code behind: Protected Sub CopyAttachments(ByVal issueId As String) Dim files As HttpFileCollection = Request.Files Dim myStream As System.IO.Stream Dim service As New SubmitService.Service For i As Integer = 0 To files.Count - 1 Dim postedFile As HttpPostedFile = files(i) Dim fileNameWithoutPath As String = System.IO.Path.GetFileName(postedFile.FileName) If fileNameWithoutPath.Length > 0 And issueId.Length > 0 Then Dim fileLength As Integer = postedFile.ContentLength Dim fileContents(fileLength) As Byte ' Read the file into the byte array. Send it to the web service. myStream = postedFile.InputStream myStream.Read(fileContents, 0, fileLength) service.ClearQuestAttachToIssue(issueId, fileNameWithoutPath, fileContents) End If Next service = Nothing End Sub When I put a breakpoint in at the declaration of service and then check the value of "files", the count is 0. I am expecting it to be 2 when i have one file uploaded. Anyone know how to fix this?

    Read the article

  • Extending a form field to add new validations.

    - by duallain
    I've written an app that uses forms to collect information that is then sent in an email. Many of these forms have a filefield used to attach files to the email. I'd like to validate two things, the size of the file (to ensure the emails are accepted by our mail server. I'd also like to check the file extension, to discourage attaching file types not useable for our users. (This is the python class I'm trying to extend) class FileField(Field): widget = FileInput default_error_messages = { 'invalid': _(u"No file was submitted. Check the encoding type on the form."), 'missing': _(u"No file was submitted."), 'empty': _(u"The submitted file is empty."), 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'), } def __init__(self, *args, **kwargs): self.max_length = kwargs.pop('max_length', None) super(FileField, self).__init__(*args, **kwargs) def clean(self, data, initial=None): super(FileField, self).clean(initial or data) if not self.required and data in EMPTY_VALUES: return None elif not data and initial: return initial # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages['invalid']) if self.max_length is not None and len(file_name) > self.max_length: error_values = {'max': self.max_length, 'length': len(file_name)} raise ValidationError(self.error_messages['max_length'] % error_values) if not file_name: raise ValidationError(self.error_messages['invalid']) if not file_size: raise ValidationError(self.error_messages['empty']) return data

    Read the article

1 2  | Next Page >