just10minutes
just10minutes

Reputation: 611

Django - Get Id of the ForeignKey Object in List View

I have two models linked by Foreign Key. RunConfig RunConfigStatus

class RunConfig(models.Model):
    config_name = models.CharField(max_length=100)

class RunConfigStatus(models.Model):
    config_run_name     = models.CharField(max_length=200,unique=True )
    config_name         = models.ForeignKey('RunConfig',on_delete=models.CASCADE,)        
    Overall_Status      = models.CharField(max_length=50,blank=True,null=True)

I am currently using a CBV list view for RunConfigStatus. I would like to href/link the foreign key object to its detail view. is this possible?

class RunConfigStatusListView(LoginRequiredMixin,ListView):
    model = RunConfigStatus
    context_object_name = 'run_config_status_list'

On my Template:

{% for run in run_config_status_list %}

 <td><a href={% url 'runconfigstatus-detail' pk=run.id %}>{{run.config_run_name}}</a></td>

  <td>{{run.config_name}}</td>                          
  <td>{{run.Overall_Status}}</td>

I want that config_name should have a href which will redirect to RunConfig detail view

 <td><a href={% url 'runconfig-detail' pk=**NOT SURE** %}>{{run.config_name}}</a></td>

Screen Shot of my current output, enter image description here

I would like to click on Config Name values and it should redirect to its detail view. (In this case Test, MyFirstTest on all entries)

Upvotes: 0

Views: 1224

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599638

Of course it's possible. You're already accessing the runconfig name, you can do exactly the same thing with the pk:

<a href="{% url 'runconfig-detail' pk=run.config_name.id %}">

However you should really pick a less confusing name for the foreign key; the field config_name doesn't point to a name, it points to a RunConfig instance.

Upvotes: 3

Related Questions