Cannot display data from the database using id = pk in django
I am trying to fetch data from the database and display it in view_data.html. I cannot seem to do it. I am not sure if i understand the use case of id = pk at this point. I want to be able to display data containing particular host when i click on the view button under the 'host' Can anyone help me display the data. Here is what I have done so far:
models.py
from django.db import models
from django.contrib.auth.models import User
class Information(models.Model):
host = models.CharField(max_length=200, null=True, blank=False)
hostname = models.CharField(max_length=200, null=True, blank=False)
port = models.IntegerField()
platform = models.CharField(max_length=200, null=True, blank=False)
username = models.CharField(max_length=200, null=True, blank=False)
password = models.CharField(max_length=200, null=True, blank=False)
groups = models.CharField(max_length=200, null=True, blank=False)
def __str__(self):
return self.host
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Information
from .forms import MyForm
def home(request):
informations = Information.objects.all()
context = {'informations':informations}
return render(request, 'polls/home.html', context)
def view_data(request, pk):
information = Information.objects.get(id=pk)
context = {'information':information}
return render(request, 'polls/view_data.html')
def my_form(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = MyForm()
return render(request, 'polls/room_form.html', {'form': form})
forms.py
from django import forms
from .models import Information
class MyForm(forms.ModelForm):
class Meta:
model = Information
fields = '__all__'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('view_data/<str:pk>/', views.view_data, name = "view_data"),
path('host/', views.my_form, name='my_form')
]
home.html
{% extends 'main.html' %}
{% block content %}
<h1>Home Template</h1>
<div>
<a href="{% url 'my_form' %}"> Add Device </a>
<hr>
<div>
{% for information in informations %}
<span>@{{information.host}}</span>
<h3>{{information.id}}<a href="{% url 'view_data' information.id %}"> view </a></h3>
<hr>
{% endfor %}
</div>
</div>
{% endblock content %}
viewdata.html
{% extends 'main.html' %}
{% block content %}
<h1>{{information.hostname}}</h1>
{% endblock content %}
Edit: I forgot to send the context in my view_data. The problem is solved now.