创建指向显示我数据库中带有django的特定行的页面的链接吗?

时间:2019-02-08 23:00:49

标签: django django-views

我根据这个问题的更复杂项目创建了一个淡化项目,以帮助更有效地提出我的问题。我将在下面为以后的读者提供以下代码,但为方便起见,here是gitlab存储库网址。

我有一个“ NotesModel”模型,可以对您白天可能要使用的笔记的体系结构进行建模。这很简单,有一个“标题”,“标签”,当然还有我称为“内容”的主要部分。该标记就像您链接到堆栈溢出帖子的标记。只是为了帮助确定特定笔记可能涉及的主题。

在基于函数的视图中,我查询数据库中的每一行,并将其交给render(.., .., {'notes': notes})函数,如下所示。通过某些html / bootstrap样式,我将数据库中“标签”列中的每个项目显示为标签,该标签可通过... a href =“” ...语法进行链接。

    {% for note in notes %}
        <span class="label label-primary" id="tags">
            <a id="theurl" href="this is where my confusion is">
            {{note.tag}}
            </a>
        </span>
    {% endfor %}

我已经输入了一些基本注释,并进行了屏幕截图,以帮助您了解页面的外观,希望它可以更好地解释我想要的行为,接下来再解释。

Screen-shot

我想要的行为是将此标签视为您可以在某些论坛网站上找到的实际标签。行为如下...

1)用户单击标签
2)Django将用户引导到另一个页面
3)将显示数据库中属性“标签”(作为列)与标签名称匹配的行。

让我解释更多。从上图可以看到,已经有四个注释(数据库术语中的四行)输入到数据库中。因此,“标签”属性(在数据库术语中为“标签”列)具有四个实例,分别是 starwars startrek avp 和另一个 starwars 实例。我希望能够单击标签 starwars ,它会将我定向到另一个页面,该页面显示带有“ tag” starwars 的所有注释。其他标签也是如此。如果我单击 startrek ,那么我希望它将我定向到另一个页面,该页面显示所有带有'tag' startrek 标记的注释。

我曾经尝试在模板文件夹中创建另一个页面,然后使用了查询集过滤器,就像我传递给模板的以下内容一样。

queryset = NotesModel.objects.filter(tag__icontains='starwars')

然后,我只是在... a href =“” ...代码段中键入了指向该页面的直接链接。但是,此解决方案有两个问题...

1仅适用于 starwars
2如果我这样做,我将不得不在我的模板文件夹中创建x数量的page.html文件,并使用上述queryset来创建x数量的基于函数的视图。这是静态的,而不是动态的处理方式,那么我该如何完成这样的任务?

以下是截至目前我项目中的文件。正如我之前说的,如果您想自己拉项目,我将在上面包括gitlab存储库URL。

the_app / urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name='home'),
]

the_app / models.py

from django.db import models
class NotesModel(models.Model):
    title = models.CharField(max_length=100, blank=True)
    tag = models.CharField(max_length=100, blank=False)
    content = models.CharField(max_length=1000, blank=False)
    def __str__(self):
        return self.title

the_app / forms.py

from django import forms
from .models import NotesModel
class NotesForm(forms.ModelForm):
    class Meta:
        model = NotesModel
        fields = ['title', 'tag', 'content']

the_app / views.py

from django.shortcuts import render
from .models import NotesModel
from .forms import NotesForm

def home(request):

    # Grab the form data
    if request.method == 'POST':
        form = NotesForm(request.POST)
        if form.is_valid():
            form.save()
            form = NotesForm()
    else:
        form = NotesForm()

    # Grab the data from the database
    notes = NotesModel.objects.all()

    return render(request, 'the_app/page_home.html', {'form': form, 'notes': notes})

the_app / templates / the_app / base.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="{% static 'mystyle.css' %}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div>
    {% block notesform %}{% endblock notesform %}
</div>
<div>
    {% block notetags %}{% endblock notetags %}
</div>
</body>
</html>

the_app / templates / the_app / page_home.html

{% extends "the_app/base.html" %}

{% block notesform %}
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock notesform %}

{% block notetags %}
    {% for note in notes %}
        <span class="label label-primary" id="tags">
            <!-- I didn't know what to put here so i used google's url as a place holder-->
            <a id="theurl" href="https://www.google.com">
            {{note.tag}}
            </a>
        </span>
    {% endfor %}
{% endblock notetags %}

1 个答案:

答案 0 :(得分:1)

这是问题所在,queryset = NotesModel.objects.filter(tag__icontains='starwars')您的标签仅包含星际大战。因此它将找不到其他标签。

class TagPostView(ListView):
   model = NoteModel
   template_name = '....'
   context_object_name = 'all_notes_of_this_tag'

   def get_queryset(self):
      result = super(PostTagView, self).get_queryset()
      query = self.request.GET.get('q')
      if query:
         postresult = NoteModel.objects.filter(tag__icontains=query)
         result = postresult
      else:
         result = None
      return result

现在,您可以将标签作为q传递,它将搜索该标签并显示结果。您只需要一个模板即可。

在可以使用的模板中,

{% for note in all_notes_of_this_tag %}
{{note.title}}
#..
{% endfor %}

这将解决所有三个要求。