Django中无法通过id=pk获取并展示数据库数据问题求助
问题:Django中点击View按钮无法展示对应主机数据,同时对id=pk的使用场景存疑
我尝试从数据库中获取数据并在view_data.html页面展示,但始终无法成功,目前我对id=pk的使用场景不太理解。我希望点击“host”下方的view按钮时,能展示对应主机的数据。以下是我目前编写的代码:
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 %}
view_data.html
{% extends 'main.html' %} {% block content %} <h1>{{information.hostname}}</h1> {% endblock content %}
补充:我忘记在view_data视图中传递context了,现在问题已经解决。
内容的提问来源于stack exchange,提问作者Super MaxLv4
相关产品推荐
相关产品推荐

