Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a model field as hyperlink in django models

class Trip(models.Model):
    trip_number = models.CharField(
        _("Trip Number"), max_length=128, db_index=True, unique=True, 
    blank=True)

what i am looking is to make this trip_number as hyperlink.

like image 886
Brijesh Avatar asked Sep 01 '17 06:09

Brijesh


People also ask

How do I add a model field in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.

What is URL field in Django?

In this article, we show how to create a URLField in Django. A URLField is a field (of a database table or a form) that stores only URLs. This could be useful for all types of reasons. One glaring example is to let a user enter his or her website.

WHAT IS models CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


2 Answers

I think you can use URLField to store hyperlinks, since this field type use URLValidator. URLField is a subclass of CharField, so you can use max_length.

class Trip(models.Model):
    trip_number = models.URLField(
        _("Trip Number"), 
        max_length=128, 
        db_index=True, 
        unique=True, 
        blank=True
    )
like image 94
Jose Luis Barrera Avatar answered Oct 17 '22 01:10

Jose Luis Barrera


in the django admin you can use a function to display the value as a link. Here an example:

@admin.register(models.Trip)
class TripAdmin(admin.ModelAdmin):
    list_display = ('id', 'trip_number', 'trip_link')

    def trip_link(self, obj):
        if obj.trip_number:
            return "<a href='%s'>Link</a>" % obj.trip_number
        else:
            return ''
like image 1
Karim N Gorjux Avatar answered Oct 17 '22 02:10

Karim N Gorjux