Search code examples
djangodjango-urls

Django. Can't get absolute url


I need a link to supplier_data for logged in supplier. Can't get it with any method. I get empty element. Model:

class Supplier(models.Model):
    id = models.IntegerField(primary_key=True)
    company_name = models.OneToOneField(User, max_length=120, on_delete=models.CASCADE)
    currency = models.CharField('Currency', max_length=4)
    legal_form = models.CharField('Legal form', max_length=100, choices=legal_form_options, default='Sole proprietorship')
    accounting_standards = models.CharField('Accounting standards', max_length=100)
    owner_structure = models.CharField('Owner structure', max_length=100)
    industry_sector = models.CharField('Industry sector', max_length=100, choices=industry_sector_options, default='Advertising')  
    date_of_establishment = models.DateField('Date of establishment', default=date.today)
    start_up = models.CharField('Start-up', choices=start_up_options, default='No', max_length=4)
    email_address = models.EmailField('Email address')
    web = models.URLField('Website address')

    def get_absolute_url(self):
        return reverse('supplier_data', args=[self.id])

View:

def all_suppliers(request):
    supplier_list = Supplier.objects.all()
    return render(request, 'all_suppliers.html',{'supplier_list': supplier_list})

def supplier_data(request, id): 
    supplier_list = get_object_or_404(Supplier, pk=id)
    return render(request, 'all_suppliers.html',{'supplier_list': supplier_list})

Url:

    path('supplier_data/<int:id>', views.supplier_data, name="supplier_data"),

Html:

        {% for supplier in supplier_list %}
        <a id=link href="{% url 'supplier_data' supplier.id %}">Supplier data</a>
        {%endfor%}

I spent about one week trying with get_absolute_url method and without it... many things... Thanks for taking a look at this.


Solution

  • check for spaces in tags {% endfor %} and remove id as it must be unique and a string like id="link1" but makes no sense here:

    {% for supplier in supplier_list %}
        <a href="{% url 'supplier_data' supplier.id %}">Supplier data</a>
    {% endfor %}
    

    and make sure that supplier_list is not empty (no objects in database created yet) e.g by placing it before the loop for debugging like:

    xxx{{supplier_list}}xxx
    {% for .... %}
    
    

    xxx just to make an empty string visible.

    if you need a unique id for some reason you can create it using the forloop counter:

    id = "link{{forloop.counter}}"
    

    no spaces in {{template_variable}} !