Home > OS >  Custom links in django
Custom links in django

Time:07-03

Here's my initial code

class Article(models.Model):
    article_author  = models.CharField(max_length=12)
    article_name    = models.CharField(max_length=60)
    article_body    = models.TextField()
    article_date    = models.DateTimeField(auto_now_add=True)
    article_tags    = models.CharField(max_length=25, choices=tags_, null=True)
    article_link    = make_link()  

Turns out it won't be added to the db, and I can't make migrations (prob. because it's not part of .models).  (I want the link to be made automatically as the instance of article class is created, and without user)

I can just make it a CharField and then replace whatever was there with the function, but that just seems like a sloppy solution, also it'll give a usless field to the default admin-panel.

CodePudding user response:

you can add a link property to your model as

class Article(models.Model):
    ...
    # article_link    = make_link()  

    @property
    def link(self):
        return make_link()

then you can access it easily just like article.link

CodePudding user response:

I would suggest generating the link on save() and store it in a CharField with editable=False, just like Willem suggested.

Docs: https://docs.djangoproject.com/en/4.0/ref/models/fields/#editable

class Article(models.Model):
    article_author  = models.CharField(max_length=12)
    article_name    = models.CharField(max_length=60)
    article_body    = models.TextField()
    article_date    = models.DateTimeField(auto_now_add=True)
    article_tags    = models.CharField(max_length=25, choices=tags_, null=True)
    article_link    = models.CharField(max_length=200, editable=False)

    def save(self):
        self.article_link = make_link()
        super().save()

Or, if the article link is following some logic, there might be no need to generate and store the link, but access it on the fly as a property.

Django has the get_absolute_url() method, not a property, for generating URLs for an model object: https://docs.djangoproject.com/en/4.0/ref/models/instances/#get-absolute-url

class Article(models.Model):
    article_author  = models.CharField(max_length=12)
    article_name    = models.CharField(max_length=60)
    article_body    = models.TextField()
    article_date    = models.DateTimeField(auto_now_add=True)
    article_tags    = models.CharField(max_length=25, choices=tags_, null=True)

    @property
    def article_link(self):
        return make_link()
  • Related