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>).
Related
when ever i add data to the form i got extra puncuation marks in the value as shown in the image.
for example - name = xyz
while saving i get name = ('xyz',)
This image is for refrence
just remove the comma you are putting after name and other field you are defining variables and that doesn't need comma .
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 have a model that contains phone numbers external_number, stored as a char field:
models.py
class PhoneRecord(models.Model):
def __unicode__(self):
return "Call to %s (%s)" % (self.external_number, self.call_date.strftime("%c"))
INBOUND = "I"
OUTBOUND = "O"
DIRECTION_CHOICES = (
(INBOUND, "Inbound"),
(OUTBOUND, "Outbound"),
)
external_number = models.CharField(max_length=20)
call_date = models.DateTimeField()
external_id = models.CharField(max_length=20)
call_duration = models.TimeField()
call_direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES, default=INBOUND)
call = models.FileField(upload_to='calls/%Y/%m/%d')
The form is cleaning and storing the data using the UKPhoneNumberField from https://github.com/g1smd/django-localflavor-UK-forms/blob/master/django/localflavor/uk/forms.py
This means that the number is stored in the database in the format 01234 567890 i.e. with a space in.
I have created a filter using django-filters which works well, when searching for partial phone number except that it doesn't filter correctly when the search term doesn't include the space. i.e.
search for 01234 returns the record for the example above
search for 567890 returns the record for the example above
search for 01234 567890 returns the record for the example above
search for 01234567890 does not return the record for the example above
Now, I could subject the form on the filter to the same restrictions (i.e. UKPhoneNumberField as the input screen, but that then takes away the ability to search for partial phone numbers.
I have also explored the possibility of using something like django-phonenumber-field that will control both the model and the form, but the validation provided by UKPhoneNumberField allows me to validate based on the type of number entered (e.g. mobile or geographical).
What I would ideally like is either
My filter to ignore spaces that are either input by the user in their search query, or any spaces that are in the stored value. Is this even possible?
Apply the validation provided by UKPhoneNumberField to another field type without having to analyse and re-write all the regular expressions provided.
Some other UK Phone number validation I have not found yet!
You could setup the filter to do something like this:
phone_number = "01234 567890"
parts = phone_number.split(" ")
PhoneRecord.objects.filter(
external_number__startswith="{} ".format(parts[0]),
external_number__endswith=" {}".format(parts[1]),
)
That way the filter is looking for the first half of the number with the space and then the second half of the number with the space as well. The only records that would be returned would be ones that had the value of "01234 567890"
I ended up adding a custom filter with a field_class = UKPhoneFilter. This means I can't search on partial numbers, but that was removed as a requirement from the project.
You should think about normalizing the data before you save them into your DB.
You could just use django-phonenumber-field which does just that.
In regarding your problem you can always use django's regex field postfix to query over regular expression.
e.g. MyModel.objects.filter(myfiel__regex=r'[a-Z]+')
I'm using Haystack 2.3.0, and I have a search index like:
class MyModelIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.EdgeNgramField(model_attr='name', boost=1.250)
short_description = indexes.CharField(model_attr='short_description', null=True, boost=1.125)
description = indexes.CharField(model_attr='description', null=True, boost=1.125)
detail_description = indexes.CharField(model_attr='detail_description', null=True)
def get_model(self):
return MyModel
I'd like to highlight only the field detail_description. I've read in the official documentation this example:
sqs = SearchQuerySet().filter(content='foo').highlight()
result = sqs[0]
result.highlighted['text'][0]
But when I try to do that I don't get the same result. In the example above, result.highlighted seems to be a dictionary where you can access the highlight of each field:
result.highlighted['text'][0]
But in my example, when I do the same, result.highlighted is not a dictionary, it is a list, and only return the highlight of the text field.
How could I set the highlight to a concrete field ?
If the number_of_fragments value is set to 0 then no fragments are
produced, instead the whole content of the field is returned, and of
course it is highlighted. This can be very handy if short texts (like
document title or address) need to be highlighted but no fragmentation
is required. Note that fragment_size is ignored in this case.
From
LINK - http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-highlighting.html
You need to see how to change this parameter in haystack.
My temporary solution right now is to do a for loop and add the highlight manually to the field, like this:
for result in sqs:
highlight = Highlighter(my_query) # my_query has the word(s) of the query
result.detail_description = highlight.highlight(result.detail_description)
A bit late here, but if you want to pass extra params to highlight, you need to pass a dict of whatever params elasticsearch would want for the highlight function, like so:
# Solr example since I'm not familiar with ES
sqs = SearchQuerySet().filter(content='foo').highlight(**{'hl.fl': 'short_description')
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")