I am working on a website-builder program.
When the user creates a new page, he has to choose a language (English, French, German for example).
In Django Admin, in the language admin, the user can set an order. The language model contains:
order = models.PositiveSmallIntegerField(default=0, verbose_name='display order')
In the page parameters in Django Admin, the user has to choose a language. The page model contains:
language = models.ForeignKey(Language, default=0, on_delete=models.PROTECT, verbose_name='language')
The problem I have is that when the user creates a new page in Django Admin, language with PK 0 is always selected by default, even though it's not the first in the list.
Language 0 is always pre-selected by Django, and the user is unable to set the default language of new pages by setting the display order of the languages.
What I want is for Django to stop selecting the 2nd or 3rd item in the pulldown and have it default to the first item like a normal pulldown.
I expect that the issue has to do with declaring that the default language is 0 in the page model, but I couldn't get it to work when I removed it.
CodePudding user response:
I think the issue is that you are conflating order
and pk
, which are both 0
, but they are not referring to the same thing - hence the order isn't as you would expect.
Firstly, you can set the order of your Language
models in the class Meta:
class Language(models.Model):
...
class Meta:
ordering = ('order',)
Secondly, you can set a default value as a callable on the language field that always gets the first value:
def get_default_language():
return Language.objects.first()
...
language = models.ForeignKey(Language, ..., default=get_default_language)
This should pre-populate the field in the Django admin with the returned value.
The main problem with using a callable as default is that you can't pass any variables to it, so it makes it far harder to filter.
If these don't fix your ordering then you might need to delve further into admin customisation.