2

Note: there is another thread on a similar problem, but this question is more detailed and the answer mentioned in the post above is not satisfactory (elaborated below)

I was trying to create a custom Django model field, where the new field will essentially be the same as a CharField but has an additional boolean attribute -- for now, just call it "public."

I have looked up this article, but I don't like the method described as it required me to construct a model from scratch. That solution is a hassle considering the number of functions I must implement to add a parameter, per the docs.

To clarify my objectives, I will like to declare this field as such:

somefield = BoolCharField(public=True, max_length=100, blank=True)
# Note that public is NOT a default CharField attribute

The documentation stated that I can extend new fields from existing ones, but the process isn't elaborated. Can anyone please provide me with an example of how I should implement my field?

This is the source code of CharField in case anybody needs a reference.

Update

I had a look at overriding the default __init__ method. Here's what the documentation suggests:

from django.db import models

class HandField(models.Field):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 104
        super().__init__(*args, **kwargs)

However, the docs didn't specify how exactly overriding works in this case (e.g. where should I throw in an additional attribute and what methods I must include), which made me post this question.

Again, as I have been stuck for quite some time, I'd prefer examples instead of concepts.

2
  • You can override the __init__(...) method, right? Commented Nov 9, 2020 at 3:32
  • @ArakkalAbu In the docs, it said that "The Field.__init__() method takes the following parameters:" with a list of arguments, and it doesn't seem like I can override the custom arguments -- I mean, if I overrode the entire method, there are no documentation to back this method up Commented Nov 9, 2020 at 4:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.