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
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].
This question already has answers here:
What is a "slug" in Django?
(13 answers)
Closed 5 years ago.
In Django generic views, there's slug_field, and slug_url_kwarg.
In this context, what is the definition of slug?
I choose the more persuasive explanation within items of 3 dictionaries.
In Cambridge dictionary:
A piece of metal used instead of a coin for putting in machines
In MW:
A disk for insertion in a slot machine; especially :one used illegally instead of a coin
In Oxford:
A part of a URL which identifies a particular page on a website in a form readable by users.
They don't seem to make sense.
It is from the publishing world from wikipedia:
In newspaper editing, a slug is a short name given to an article that
is in production. The story is labeled with its slug as it makes its
way from the reporter through the editorial process. The AP Stylebook
prescribes its use by wire reporters (in a "keyword slugline") as
follows: "The keyword or slug (sometimes more than one word) clearly
indicates the content of the story."[1] Sometimes a slug also contains
code information that tells editors specific information about the
story — for example, the letters "AM" at the beginning of a slug on a
wire story tell editors that the story is meant for morning papers,
while the letters "CX" indicate that the story is a correction to an
earlier story.[2][3] In the production process of print
advertisements, a slug or slug line, refers to the "name" of a
particular advertisement. Advertisements usually have several markers,
ad numbers or job numbers and slug lines. Usually the slug references
the offer or headline and is used to differentiate between different
ad runs.
From there, the slug for web publishing was born as an effort to make more semantic URLs. This is the slug as used in django:
Some systems define a slug as the part of a URL that identifies a page
in human-readable keywords.[4][5] It is usually the end part of the
URL, which can be interpreted as the name of the resource, similar to
the basename in a filename or the title of a page. The name is based
on the use of the word slug in the news media to indicate a short name
given to an article for internal use. Slugs are typically generated
automatically from a page title but can also be entered or altered
manually, so that while the page title remains designed for display
and human readability, its slug may be optimized for brevity or for
consumption by search engines. Long page titles may also be truncated
to keep the final URL to a reasonable length. Slugs are generally
entirely lowercase, with accented characters replaced by letters from
the English alphabet and whitespace characters replaced by a dash or
an underscore to avoid being encoded. Punctuation marks are generally
removed, and some also remove short, common words such as
conjunctions. For example:
Original title: This, That and the Other! An Outré Collection
Generated slug: this-that-other-outre-collection
Django provides a slug field, and in its documentation provides a definition as well:
Slug is a newspaper term. A slug is a short label for something,
containing only letters, numbers, underscores or hyphens. They’re
generally used in URLs.
Imagine it is for translating vocabulary to another language. I'm only dealing with a limited number of words (~2000).
Language1 and Language2 (which will have a different ~2000 words), each might have multiple words equivalents from the other language which may or may not be on the list of ~2000 words of the other language.
Using a many-to-many relationship initially appealed to me, but I can't quite see through the mist to see what would work best.
My other thought was just making a json dump for each word. Something like....
{1: {'Lang1': [word1, word2], 'Lang2': [word1, word2]}}
but I am not sure if that is too smart to manage everything like that, it would be cumbersome to do from the admin section (because I think I would be editing a long line of text that is a json object) and it doesn't take advantage of much.
Maybe there is another way that I havent thought of?
Given my scenario, how would you go about defining this?
class Language(models.Model):
name = models.CharField(max_length=100)
class Word(models.Model):
name = models.CharField(max_length=100)
language = models.ForeignKey(Language, related_name='language_words')
#...
class Translation(models.Model):
word = models.ForeignKey(Word, related_name='word_translations')
translation = models.CharField(max_length=100)
from_language = models.ForeignKey(Language, related_name='language_translations')
in_language = models.CharField(max_length=100)
# stage performances
english_language = Language(name='english')
english_language.save()
word = english_language.language_words.create(name='Flower')
german_translation = word.word_translations.create(translation='Blumen',
from_language=english_language,
in_language='German')
word # 'Flower'
german_translation # 'Blumen'
might not be optimal yet, i am in the train right now, but this can be a good way to start hopefully.
then if you register these models into admin, you can easily manage (add/delete) translations..
So this might be an obvious answer to some but I'm not sure what the right answer is. I have a simple donation application where Donor objects get created through a form. A feature to be added is to allow of a search for each Donor by last name and or phone number.
Is this a good case to use django-haystack or should I just create my own filters? The problem I may see with haystack is that a few donations are being submitted every minute so could indexing be a problem? There are currently around 130,000 records and growing. I have started to implement haystack but have realized it might not be necessary?
Don't use haystack -- that's for fast full-text search when the underlying relational database can't handle it easily. The use case for haystack is when you store many large documents with huge chunks of text that you want indexed by words in the document so you can easily search.
Django by default already allows you to easily index/search text records. For example, using the admin backend simply specify search fields and you can easily search for name or telephone number. (And it will generally do case insensitive contains searches -- this will find partial matches; e.g., the name "John Doe" will come up if you search for just "doe" or "ohn").
So if your models.py has:
class Donor(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=15)
and an admin.py with:
from django.contrib import admin
from mysite.myapp.models import Donor
class DonorAdmin(admin.ModelAdmin):
model = Donor
search_fields = ['name', 'phone']
admin.site.register(Donor, DonorAdmin)
it should work fine. If an improvement is needed consider adding an full-text index to the underlying RDBMS. For example, with postgres you can create either a text search indexes post 8.3 with a one liner in the underlying database, which django should automatically use: http://www.postgresql.org/docs/8.3/static/textsearch-indexes.html
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")