I'm using the following code in a django model to format a column in the admin interface:
def formatted_mu(self):
return "%.1f%%" % self.mu
formatted_mu.short_description = u'\u03BC'
For some reason instead of showing µ in the heading, it shows M. I know this should work as when I tried u'\u03A3' I did receive ∑.
Encoding reference:
Encoding for ∑
Encoding for µ
UPDATE:
I've discovered that other lower case Greek letters are switched with their capital counterparts too. Is there any way to avoid this?
That M is a capital Mu. Sigma looks distinctive, but capital-Mu looks like our M.
Django capitalizes the first letter of any field
You can avoid capitalizing a model name by setting a verbose_model_plural in the Meta class of your model definition in models.py with the setting as you want and a space as the first character.
E.g.,
class SomeModel(models.Model):
class Meta:
verbose_name_plural = u' \u03BC'
EDIT1: My initial solution didn't work, as django always capitalizes the first letter even in a verbose_name_plural (though it won't automatically convert the other letters to lowercase like the admin normally does to model names.) However, making the first letter of the verbose name be a space, it works. Note since the name is in a html table (which ignores whitespace before the first/last character) the space in the verbose model name doesn't get noticed to the user.
EDIT2: Or to avoid capitalizing a field name (sorry -- didn't read question carefully).
class AnAverageModel(models.Model):
mean = models.FloatField(u" \u03BC")
Related
So, I came across this when I was working on a project.
I had mistakenly placed a "," after a field in one of my models and Django did all the migrations while ignoring that particular field. It took me a while to realize that a little "," after the field is responsible for my field not being reflected in the database.
However, I understand that there shouldn't be a coma but I was kind of expecting Django to give me an error or at least a warning.
Something like maybe:
"Invalid syntax in models.py near FieldName"
EDIT:
"one or more model fields are stored as tuple/s are you sure you want to do so?"
But it ignores that particular field and keeps on migrating. My question is why does Django let that happen? Is this the expected behaviour and shouldn't Django notify for such things? or why this is being passed silently.
Here is an example to have a look at.
class person(models.Model):
name = models.CharField(max_length=10)
surname = models.CharField(max_length=10),
age = models.PositiveIntegerField()
Now, if you create migrations and apply them Django will simply ignore the surname field here and apply the migrations without any errors, why is it so?
It is not invalid syntax. By adding a trailing comma, you wrap the field in a singleton tuple. So the type of person.surname is tuple.
For example if you write:
>>> a = 1,
>>> a
(1,)
>>> type(a)
<class 'tuple'>
A model can, besides the model fields contain all sorts of things: constants, subclasses, methods, etc.
One could do an exhaustive search in all the fields, etc. to check if a tuple wraps a model field, but that could take considerable time, it might result in evaluating lazy attributes, and it might even get stuck in an infinite loop.
It might however be something that can be added to flake8-django [GitHub].
So, in my Django projects, I made my model to be like the following
class Store(models.Model):
domainKey = models.CharField()
I had the above to make each store has its own domain like the following
www.domain.com/my-name-is-django
Anyway, it was perfectly working fine. But, I just found out SlugField() which is used for the same purpose as what I did in above.
My question is why we need to use SlugField() because I implemented the same thing without SlugField(). Is there its own any feature that CharField() doesn't have?
A slug is a string without special characters, in lowercase letters and with dashes instead of spaces, optimal to be used in URLs. An example of slug could be:
example/this-is-a-slug/150
you can look for more information here Documentation django slug
CharField has max_length of 255 characters , and accept special characters.
About CharField Here
I would like to know if there is a solution in order to make multiple newlines in my Django Charfield Form.
I have a field Description and I would like to write something inside like :
Hello,
My name is John.
I am 23 years old.
Is it possible to help me ?
Unfortunately, up to now I have :
Hello, My name is John. I am 23 years old. Is it possible to help me ?
My models looks like :
class Ticket(models.Model):
...
Description = models.CharField(max_length=250, verbose_name='Description')
When users are filling Description Field, I would like to set in real-time newlines. As you can see, all strings are in the same line.
How I could do that ?
I found a solution. I replaced models.CharField by models.TextArea :
Description = models.TextField(max_length=250, verbose_name='Description')
Then in my template, I set :
{{value|linebreaks}}
And it works ! I can make newlines with Caps + Enter
I had a use case where I wanted allow newline characters to be rendered, as well as to restrict the number of characters in the field to a fixed number (Similar to adding a bio field to a profile).
You can combine certain concepts from Templates and Forms to achieve this.
In your model, define the field as a normal CharField:
description = models.CharField(max_length=250)
In your form, initialize the field as follows:
description = forms.CharField(max_length=250, widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
Using the widget as Textarea is important here, because if you use the default TextInput widget, it will submit the form on pressing Enter, rather than inserting a newline. You can change the size of the Textarea to be rendered by using an attrs dict.
Now, finally to display the content correctly with newlines, inside your template, apply the linebreaks Django filter:
<p>{{ user.profile.description|linebreaks }}</p>
The linebreaks filter replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br>) and a new line followed by a blank line becomes a paragraph break (</p>).
Given a model with both Boolean and TextField fields, I want to do a query that finds records that match some criteria AND have more than "n" words in the TextField. Is this possible? e..g.:
class Item(models.Model):
...
notes = models.TextField(blank=True,)
has_media = models.BooleanField(default=False)
completed = models.BooleanField(default=False)
...
This is easy:
items = Item.objects.filter(completed=True,has_media=True)
but how can I filter for a subset of those records where the "notes" field has more than, say, 25 words?
Try this:
Item.objects.extra(where=["LENGTH(notes) - LENGTH(REPLACE(notes, ' ', ''))+1 > %s"], params=[25])
This code uses Django's extra queryset method to add a custom WHERE clause. The calculation in the WHERE clause basically counts the occurances of the "space" character, assuming that all words are prefixed by exactly one space character. Adding one to the result accounts for the first word.
Of course, this calculation is only an approximation to the real word count, so if it has to be precise, I'd do the word count in Python.
I dont know what SQL need to be run in order for the DB to do the work, which is really what we want, but you can monkey-patch it.
Make an extra fields named wordcount or something, then extend the save method and make it count all the words in notes before saving the model.
The it is trivial to loop over and there is still no chance that this denormalization of data will break since the save method is always run on save.
But there might be a better way, but if all else fails, this is what I would do.
I have a ModelForm, in which I'm having a CharField, which is declared as unique in the Model.
But I have 2 problems:
If I fill in the form with a field having the same name I don't get an error message.
I'd like this field not to contain white spaces.
Is it possible to do that using a ModelForm?
You can do something close to this:
class MyModelForm(forms.ModelForm):
# your field definitions go here
def clean_myuniquefield(self):
# strip all spaces
data = str(self.cleaned_data['myuniquefield']).replace(' ', '')
model = self._meta.model
# check if entry already exists
try:
obj = model.objects.get(myuniquefield=data)
except model.DoesNotExist:
return data
raise forms.ValidationError("Value already exists!")
To get rid of spaces, make a clean_fieldname function to strip the spaces.
http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation
As for uniqueness, also note about the meta-field unique_together. I don't know if you need it, but I didn't know about it until I dug around.
If you really need to do uniqueness checking before trying to add and failing, you can also do that in the clean_* function. However, it might be better to assume that the database will take care of it and fail in a standard way, and just set up your error messages properly. That way, if you change constraints later, it will flow through more easily. And if others have to maintain your code, it will be more standard.
Hope this helps.