Home > Back-end >  How to concatenate string in django framework
How to concatenate string in django framework

Time:05-05

I want to concatenate a string to get a product link in one of my django datatable columns.

I want a result like this: https://www.aliexpress.com/item/1005003324927716.html

The product id is stored in my mongodb database. This is what I tried to write in my datatable.html but i get an empty column:

 {% for product in products %}
  <tr>
<td> 
 {% with "https://www.aliexpress.com/item/"|add:{{product.productId}}|add:".html" as template %}
 {% endwith %}
</td>
  </tr>
{% endfor %}

Then to make it as an href link as this syntax :

<td><a href="{{product.Productlinks }}"> Click here</a></td>

views.py :

def datatable_view(request):
    client = MongoClient("mongodb://localhost:27017/")
    db = client["aliexpress"]
    col = db["listproducts"]
    products = col.find()
    context = {'products' : products}
    return render(request,'datatable.html', context)

models.py :

class Datatable(models.Model):

    Title = models.CharField('Title',max_length=500),
    Price = models.DecimalField('Price',decimal_places = 3, max_digits = 10000),
    Currency = models.CharField('Currency',max_length=500),
    Stars = models.DecimalField('Stars',decimal_places = 3 , max_digits = 10000),
    Orders = models.PositiveIntegerField('Orders',max_length=500),
    Shipcost = models.CharField('Shipcost',max_length=500),
    Supplier = models.CharField('Supplier',max_length=500),
    Productlinks = models.CharField('Productlinks',max_length=700)

I am pretty new in using django and I will be so grateful if you help me in this isuue. Thank you !

CodePudding user response:

Make it simple, add a property in your Product model

class Product(models.Model):
    ...
    @property
    def link(self):
        return 'https://www.aliexpress.com/item/'   str(self.productId)   '.html'

<td><a href="{{product.link}}"> Click here</a></td>

UPDATE

You can make it even more simpe by doing this :

<td><a href="https://www.aliexpress.com/item/{{product.productId}}.html">Click here</a></td>

CodePudding user response:

use this:

{% with "https://www.aliexpress.com/item/"|add:{{product.productId}}|add:".html" as template %}
{% include template %}
{% endwith %}
  • Related