w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I capitalize the first letter in an array of strings using method capitalize?
Try this: puts fan_info.map(&:capitalize) This calls #capitalize on every string, builds a new array of all the results, and prints that out instead. It's equivalent to something like this: fan_info_capitalized = [] fan_info.each do |inf| fan_info_capitalized << inf.capitalize end puts fan_info_capitalized Only much more compact.

Categories : Ruby

Django: Help using ModelChoiceField
forms.py: class MyForm(forms.Form): # or with some filter applied my_field = forms.ModelChoiceField(queryset=Equipment.objects.all()) Then just use {{ form.as_<whatever you want> }} in your template and it should work.

Categories : Django

ModelChoiceField and templates
A cleaner way to hide the author from the form would be class AddNewsForm(ModelForm): class Meta: model = News exclude = ('author', ) and in the views: @login_required def myView(request): #some code here if request.POST: form = AddNewsForm(request.POST) if form.is_valid(): news = form.save(commit=False) news.author = request.user news.save() #rest of the code and let the template load the default way {{ form.as_p }}

Categories : Django

Django ModelChoiceField has no plus button
You need to set a RelatedFieldWidgetWrapper wrapper in your model form: The RelatedFieldWidgetWrapper (found in django.contrib.admin.widgets) is used in the Admin pages to include the capability on a Foreign Key control to add a new related record. (In English: puts the little green plus sign to the right of the control.) class MyCustomUserCreationForm(models.ModelForm) ... location = forms.ModelChoiceField(queryset=Location.objects.all()) def __init__(self, *args, **kwargs): super(MyCustomUserCreationForm, self).__init__(*args, **kwargs) rel = ManyToOneRel(self.instance.location.model, 'id') self.fields['location'].widget = RelatedFieldWidgetWrapper(self.fields['location'].widget, rel, self.admin_site) I could make a mistake in the example

Categories : Python

Overriding Django's ModelChoiceField
Rename your class other than ModelChoiceField , Please take care of the remaining logic class CustomModelChoiceField(django.forms.ModelChoiceField): """Subclasses Django's ModelChoiceField and adds one parameter, `obj_label`. This should be a callable with one argument (the current object) which returns a string to use as the label of that object or instance.""" def __init__(self, obj_label=None, *args, **kwargs): super(CustomModelChoiceField, self).__init__(*args, **kwargs) self.obj_label = obj_label def label_from_instance(self, obj): if self.obj_label: return self.label(obj) return super(CustomModelChoiceField, self).label_from_instance(obj)

Categories : Python

How to write view from ModelChoiceField response?
It looks like you're mixing forms.Form and forms.ModelForm in class season_choice based on your use of forms.Form but also declaring a Meta class. If you need a different form widget than the model default, you can over ride it in the Meta class if using a ModelForm. When using ModelForms it's best practice to explicitly list the fields to be displayed so that future fields (potentially sensitive ones) are not added by default. class SeasonForm(forms.ModelForm): class Meta: model = Season fields = ['year'] widgets = { 'year': forms.widgets.Select(), } Django models also have a Meta class that will allow you to provide a default ordering: class Season(models.Model): year = ... class Meta: ordering = ['-year'] If you don

Categories : Django

django modelchoicefield select columns
Use .only() method instead of .values(): https://docs.djangoproject.com/en/1.5/ref/models/querysets/#django.db.models.query.QuerySet.only

Categories : Django

Using ModelChoiceField and queryset argument using Django
You've misunderstood the answer to that question, or maybe my comment on that answer. You would only use a ModelChoiceField if the choice needs to get its values from a model - my comment was only to point out that you can do that whether or not the form itself is based on a model. But in your case, the choice has nothing to do with any model, so ModelChoiceField is the wrong option. A standard ChoiceField is the way to go here: class MemberRegistrationForm(forms.ModelForm): year = forms.ChoiceField(choices=[]) def __init__(self, *args, **kwargs): super(MemberRegistrationForm, self).__init__(*args, **kwargs) year = datetime.datetime.now().year self.fields['year'].choices = [(i, i) for i in range(year-20, year+1)]

Categories : Python

Django ModelChoiceField pre-filled with data?
Looks like your setting of purchase_order based on the url is in the request.POST condition which will only set when the form is posted. Move the initial value setting down to the else condition. else: form = Phase2Form(initial={'purchase_order': PurchaseOrder.objects.get(pk=po) }) return render(request, 'input.html', {'input_type': 'Phase 2','formset': form,})

Categories : Django

How do i render a form ModelChoicefield's attributes in django?
Unfortunately ModelChoiceField's iterator only returns tuple (value, label), so you need to make some overriding to make it work, this link should help you out: http://srcmvn.com/blog/2013/01/15/django-advanced-model-choice-field/

Categories : Django

Django - ModelChoiceField empty choice missing
You will only get the 'free' empty option if you allow django forms to render the form field automatically. Because you are rendering it yourself in your template (and I don't know why you would want to do that...) you would need to add the empty select yourself: <select name="startAddr"> <option value="">-----------</option> {% for location in form.fields.startAddr.queryset %} <option value = "{ location.location_name }">{{location.location_name}}</option> {% end for %} </select> You can test this by allowing django form to render it for you: <div>Start Address</div> {{ form.startAddr }}

Categories : Python

Django filter the queryset of ModelChoiceField - what did i do wrong?
In you views.py, you have this line: form = AddGame(request.POST or None, instance=game) So form is a Form object of class AddGame (Side note: you should change the name to AddGameForm to avoid confusion). Since home_team is a field in AddGame class, it's not an attribute in form object. That's why you can't access it via form.home_team. However, Django Form API provides fields attribute to any form object, which is a dict contains all form fields. That's why you can access form.fields['home_team']. And finally since home_team is a ModelChoiceField, it can contain a queryset attribute, that's why you can access form.fields['home_team'].queryset

Categories : Django

Django show ManyToMany field of model using ModelChoiceField
You can't just display a form field on its own. It has to actually be part of a form, which you must instantiate before passing it to the template. Also note that your method for getting the parent is horribly inefficient: you instantiate every single Parent in the database, just to get one. You should query it directly. class ParentForm(forms.Form): media = forms.ModelChoiceField(Media.objects.none(), widget=forms.Select()) def __init__(self, *args, **kwargs): parent = kwargs.pop('parent') super(ParentForm, self).__init__(*args, **kwargs) self.fields['media'].queryset = parent.media.all() def my_view(request): parent = Parent.objects.filter(name=request.session['current_parent']) form = ParentForm(parent=parent) return render_to_response

Categories : Python

Django Stale Model Objects and Forms ChoiceField vs ModelChoiceField
the stale version class body should be inside __init__ method! – mariodev Thank you mariodev. Following this lead, I was able to generate code that functioned properly. My first attempt still failed to work properly: class GetDocumentForm(forms.Form): def __init__(self): ... self.base_fields['document'].choices = self.document_choices[:] This would allow me to create a form, but when I attempted to render: In [1]: from WebSite.forms import * In [2]: doc_form = GetDocumentForm() In [3]: print doc_form.as_p() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) AttributeError: 'GetDocumentForm' object has no attribute '_errors' The solution is here: StackOve

Categories : Django

How to Capitalize first letter only using CSS in each case
It is not possible with CSS alone but you can do it with Javascript or PHP for example. In PHP ucwords() And in Javascript function toTitleCase(str){ return str.replace(/wS*/g, function(txt){ return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); } Extracted from Convert string to title case with javascript

Categories : CSS

Capitalize the first letter of sentences in paragraphs
Try out the following code: <style> p:first-letter { text-transform: uppercase; } </style> <?php function upperFirstWord($str) { return preg_replace('/([.!?])s*(w)/e', "strtoupper('\1 \2')", ucfirst(strtolower($str))); } echo upperFirstWord("<p>THIS IS THE FIRST SENTENCE. THIS IS THE SECOND SENTENCE! THIS IS THE THIRD SENTENCE.. THIS IS THE FOURTH SENTENCE! IS THIS THE FIFTH SENTENCE?</p><p>THIS IS THE FIRST SENTENCE. THIS IS THE SECOND SENTENCE! THIS IS THE THIRD SENTENCE.. THIS IS THE FOURTH SENTENCE! IS THIS THE FIFTH SENTENCE?</p>"); ?> Hope this will help. Thank you :-)

Categories : PHP

undefined method `capitalize' for nil:NilClass
The error is telling you that you are calling capitalize method on nil. I see 2 potentials issues here: Using find_by_name What if params[:subcat] is nil or params[:cat] is nil Using find_by_name will not raise an exception if no record is found, nil will be returned. Your conditions checking if params[:cat] or params[:subcat] are defined are not right. nil value can occur if some params are missing. You might want to check: if params[:cat].blank? # ... end if params[:subcat].blank? # ... end I would also use blank? instead of empty? (checking for both nil and "").

Categories : Ruby On Rails

Capitalize the first letter in each string in a list
Just call capitalize on each string. Note that it lowercases the rest of the letters l = ['This', 'is', 'a', 'list'] print [x.capitalize() for x in l] ['This', 'Is', 'A', 'List'] If you need to preserve case on the other letters, do this instead l = ['This', 'is', 'a', 'list', 'BOMBAST'] print [x[0].upper() + x[1:] for x in l] ['This', 'Is', 'A', 'List', 'BOMBAST']

Categories : Regex

Rails - using capitalize on a month name from l18n
If you call capitalize it only takes the first character, so you may use titleize <%=(l Date.today, format: :long) %> => "Miércoles, 28 de agosto de 2013" <%=(l Date.today, format: :long).titleize %> => "Miércoles, 28 De Agosto De 2013" Please note that all the words are turned to capital letter Update $ rails c Loading development environment (Rails 4.0.0) >> helper.l Date.today, format: :long => "September 02, 2013" >> helper.l Time.now, format: :long => "September 02, 2013 22:56"

Categories : Ruby On Rails

Capitalize first letter of each word in a selection using vim
You can use the following substitution: s/<./u&/g < matches the start of a word . matches the first character of a word u tells Vim to uppercase the following character in the substitution string (&) & means substitute whatever was matched on the LHS

Categories : Regex

JSON object: Get all objects to capitalize their first letters
If I understood it right, you need to iterate over all keys for all objects in "json.resultVal.data". Try using a for/in loop to iterate over the "data" object, as in: for( var i in json.resultVal.data ) { for( var k in json.resultVal.data[i] ) { /* here "k" will be key string ("generatedName", "generatedValue", ...) */ } }

Categories : Javascript

How to capitalize the first letter of a paragraph with jquery but no symbols?
I think you're looking for the ':first-letter css pseudo-element If you add css like so: .single .the_content p:first-letter { font-size: 2em; color: #80ffff; } Or something of the sort, that should cover it. ( oh, right, with the :first-child css pseudo-element )

Categories : Jquery

Unix command to capitalize first letter of file name
This is a shell script that will find *.java files in the local directory and alter them: #!/bin/sh find . -name "*.java" -print | gawk -F "/" ' { new = sprintf( "%s%s", toupper( substr( $NF, 1, 1 ) ), substr( $NF, 2 ) ) cmd = sprintf( "mv %s %s", $NF, new ) # comment out the next two lines and uncomment the printf() to see the commands cmd | getline ret_val close( cmd ) #printf( "%s => ret_val = %s ", cmd, ret_val"" ) } ' I saved it to a script named "alterjava", "chmod +x alterjava" then ran it on a directory of zero sized files I made up for testing. You can check the commands before running it by commenting out the cmd line and uncommenting the printf() line

Categories : Unix

Python: Capitalize a word using string.format()
You can create your own subclass of string.Formatter which will allow you to recognize a custom conversion that you can use to recase your strings. myformatter.format('{user!u} did la-dee-dah on {date}, and {pronoun!l} liked it. ', user=x, date=y, pronoun=z)

Categories : Python

how to capitalize first letter of a dynamic button string
Use String title = header.getCategoryTitle().toSubString(0,1).toUperCase); title += header.getCategoryTitle().toSubString(1).toLowerCase); headerButton.setText(title);

Categories : Android

Capitalize first letter of TextView in an Android layout xml file
No. But you can create a simple CustomView extending TextView that overrides setText and capitalizes the first letter as Ahmad said like this and use it in your XML layouts. import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; public class CapitalizedTextView extends TextView { public CapitalizedTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setText(CharSequence text, BufferType type) { if (text.length() > 0) { text = String.valueOf(text.charAt(0)).toUpperCase() + text.subSequence(1, text.length()); } super.setText(text, type); } }

Categories : Android

Javascript capitalize first letter of each word in a string only if lengh > 2
This must do the job: str = str.toLowerCase().replace(/[a-z](?=[a-z]{2})/g, function(letter) { return letter.toUpperCase(); } ); [EDIT] The above example is a little naive since it assumes that there is only letters in the string, and doesn't take account that a word boundary  can match the limit between a word character [a-zA-Z0-9_] and a non word character or an anchor. Thus, to be more rigorous, it's better to write: str = str.toLowerCase().replace(/([^a-z]|^)([a-z])(?=[a-z]{2})/g, function(_, g1, g2) { return g1 + g2.toUpperCase(); } ); If you want to do the same but this time, including the first letter of the string (whatever the number of letters after) you can use this: str = str.toLowerCase().replace(/([^a-z])([a-z])(?=[a-z]{2})|^([a-z])/g, function(_, g1, g2, g3

Categories : Javascript

whats wrong with my capitalize letters in words code?
When your function is called, the very first thing it's doing is: return str.charAt(0).toUpperCase()+ str.slice(1); This returns the first character of the string converted to upper case, plus the rest of the string (as is) starting from index 1. Since the function returns from there, nothing else in your function is being executed. How about something like: function LetterCapitalize(str) { var words = str.split(' '); // create an array of each word for(var i = 0; i < words.length; i++) // Loop through each word words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); // capitalize first character of each word return words.join(' '); // join the array back into a string } Also, if you're simply trying to do this for display purposes, you can use the

Categories : Javascript

Django ModelChoiceField show specific field and not the pk field
Right from the docs: The unicode method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it. For example: So two options: # in your model def __unicode__(self): return unicode(self.uuid) or, much better if you need to keep a different string representation: from django import forms class UUIDChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return unicode(obj.uuid) class FormWithUUIDChoiceField(forms.form): field1 = UUIDChoiceField(queryset=..., ...)

Categories : Django

Need to change capitalize python to interpret 3 different types of inputs the SAME with the raw_input function
You can use a regular expression filter to eliminate the part of the string containing "(new)": import re def myfilter(x): return ' '.join(re.sub(ur'(s*[nN][eE][wW]s*)','',x).title().split()) wcity = myfilter( raw_input("Please enter a city ==> ") ) print wcity wtype = myfilter( raw_input("Please enter a restaurant type ==> ") ) print wtype

Categories : Python

Django: custom widgets in custom modelchoicefield
I think that will do: tutor = UserModelChoiceField( User.objects.filter(groups__name='teachers') widget=Select(attrs={'class': 'form-control'}) ) Although if you're gonna use bootstrap in more places, you should consider crispy-forms or similar library.

Categories : Django

Django: How to use django.forms.ModelChoiceField with a Raw SQL query?
Are you sure you actually need a raw query there? Just looking at that query, I can't see any reason you can't just do it with filter(location__city=city_id, available_reserves__gte=0, datetime_from__gt=datetime.datetime.now()). Raw query sets are missing a number of methods that are defined on conventional query sets, so just dropping them in place isn't likely to work without writing your own definitions for all those methods.

Categories : Django

jquery dialog position not working with width:auto - need to auto resize after opening
solved it with the help of this question: jQuery - Dialog auto-resize on dynamic content and maintain center position ajaxStop is called whenever ajax finishes loading, so I'm resizing the dialog when ajaxStop is called and it's works perfectly! $(document).ajaxStop(function(){ $(".dialog").dialog({height:"auto",width:"auto"}); });

Categories : Jquery

C++11 Range-based for-loop efficiency "const auto &i" versus "auto i"
Yes. The same reason if you only ever read an argument you make the parameter const&. T // I'm copying this T& // I'm modifying this const T& // I'm reading this Those are your "defaults". When T is a fundamental type (built-in), though, you generally just revert to const T (no reference) for reading, because a copy is cheaper than aliasing. I have a program that I'm developing in which I'm considering making this change throughout, since efficiency is critical in it Don't make blind sweeping changes. A working program is better than a fast but broken program. How you iterate through your loops probably won't make much of a difference; you're looping for a reason, aren't you? The body of your loop will much more likely be the culprit. If efficiency is

Categories : C++

auto zoom and auto center to show all markers in window
From your question, it seems your using multiple markers and you want to set zoom level. If so my suggestion is to take a look at fitBounds(). fitBounds() method adjusts the map's viewport in order to view the passed LatLngBounds in full at the centre of the map. Check out this sample fiddle for demo.

Categories : Javascript

Auto layout: auto update constraints when some view is empty
Does it need to change when content is visible? If not try this: you could do an update in the viewWillAppear method. For each label, call [firstLabel setNumberOfLines:0]; [firstLabel setText:newProductTitleText]; [firstLabel sizeToFit]; Setting number of lines to 0 lets the label dynamically use an many lines as it needs. If this is an empty label that should actually become 0 lines. This will update the frames and autolayout should take care of the rest.

Categories : IOS

How to capitalize each word after a space leaving the rest of it as is and preserve the space in the end if it exists
Use re.sub: >>> import re >>> re.sub(r'[a-z]', lambda m: m.group().upper(), 'home swe eeeet home') 'Home Swe Eeeet Home' >>> re.sub(r'[a-z]', lambda m: m.group().upper(), 'heLLo OoO ooo ') 'HeLLo OoO Ooo ' re.sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function. If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. [a-z] match any lowercase character([a-z]) after the word boundary (). The lambda function

Categories : Python

Replace letters in string with the next letter, and capitalize vowels in the changed string
There are several issues. The main one is that you could inadvertently change the same letter several times. Let's see what happens to the s in sent. You first change it to t. However, when it comes to changing the final letter, which is also t, you change the first letter again, this time from t to u. Another, smaller, issue is the handling of the letter z. Finally, your indexing in the second if is off by one: d becomes D and not E.

Categories : Javascript

How do I capitalize all words in a string apart from small words in the middle and in the beginning?
It’s easiest to just forget about the special case of the first letter initially and then handle it after doing everything else: def title(sentence) small_words = %w[on the and] capitalized_words = sentence.split(' ').map do |word| small_words.include?(word) ? word : word.capitalize end capitalized_words.first.capitalize! capitalized_words.join(' ') end This also capitalizes any “small word” at the beginning, not just “the”—but I think that’s probably what you want anyway.

Categories : Ruby

Capitalize the text in textfield as user types it without using css text-transform?
On keyup event. Just apply the method to convert to uppercase this.value.toUpperCase(); Check Fiddle But if you want the text to be in uppercase just before submitting the data. Then it is better you convert to upperCase once instead of binding it in keyup event.. // submit here var data = $('#input')[0].value.toUpperCase(); Change Event fiddle $("input").on('keyup', function(e) { if( [8,37,38].indexOf(e.keyCode) > -1 ) { return; } this.value = this.value.toUpperCase(); }); Another fiddle You can use the keycode and check if either backspace or arrow keys are pressed. Else capitalize or return it.

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.