【问题标题】:How to link two model in django and fetch data from them in template如何在 django 中链接两个模型并在模板中从它们中获取数据
【发布时间】:2021-09-19 01:25:06
【问题描述】:

如果我创建模型名称数学,我会创建两个模型名称主题和部分数学只链接与数学有关的部分打开没有其他部分打开我想你明白了所以这是我的代码 我的模型.py

class Subject(models.Model):
    name = models.CharField(max_length=80, blank=False,)
    thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False)
    total_Section = models.FloatField(default='0')
    joined_date = models.DateTimeField(default=timezone.now,editable=False)
    update_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Section(models.Model):
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    sub_section = models.CharField(max_length=500, blank=True)
    title = models.CharField(max_length=5000, blank=False)
    teacher = models.CharField(max_length=500, blank=False)
    file = models.FileField(upload_to='section_vedios', blank=False)
    price = models.FloatField(blank=False)
    content_duration = models.DurationField(blank=False)
    joined_date = models.DateTimeField(default=timezone.now,editable=False)
    update_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

主题的我的views.py

@login_required
def home(request):
    subject_list = Subject.objects.all()
    return render (request, 'home.html', {'subject_list': subject_list })

我的views.py 部分

@login_required
def sections(request):
    return render (request, 'sections.html',)

我的 html 主题它有效

<ul>
      {% for subject in subject_list %}
     <li class="sub"> <a name='thumb' class="thumb" href="{% url 'subjects:section' %}"><img class="thumbnail"  src="{{ subject.thumbnail.url }}" alt=""> 
        <span><strong> {{ subject.name }} </strong> </span> </a>
        <p>No of Section : {{ subject.total_section }} </p> </li>
      {% endfor %}
    </ul>

通过点击链接根据主题查看部分的我的 html 没有显示任何内容

<li class="sub"> <a name='thumb' class="thumb" href="#">
    <span><strong> {{ subject.section.title }} </strong> </span> </a>
    <p>Name: {{ subject.section.teacher }} </p> {{ subject.section.price }} </li>
    </div>

我的 urls.py 用于呈现主题的主页 html

urlpatterns = [
    path('Register/',views.register,name='register'),
    path('', views.my_login, name='login'),
    path('logout/',views.user_logout,name='logout'),
    path('SectionWise/',views.home,name='home'),
    path('edit-profile/',views.edit_profile,name='edit')
]

我的 urls.py 部分

urlpatterns = [
    path('Section/', views.sections, name='section'),
    path('add_section/',views.add_sections,name='add_section')
]

我尝试使用上述方法,例如主题,但在每个链接中,无论您单击哪个主题链接,它都会显示所有部分

按要求添加

urls.py

urlpatterns = [
    path('section/<int:section_id>/', views.sections, name='section'),
    path('add_section/',views.add_sections,name='add_section')
]

我的家.html

{% for subject in subject_list %}
      <a href="{% url 'subjects:section' subject.section.id %}">
      <div class="card" style="width: 18rem;">
        <img src="{{ subject.thumbnail.url }}" class="card-img-top"       alt="...">
        <div class="card-body">
          <h5 class="card-title">{{subject.id}} {{ subject.name }}</h5>
          <p class="card-text">{{ subject.about }}</p>
          
          <hr>
          <p class="number" > No of Section:<strong> {{ subject.total_Section }}</strong></p>
          <p class="last"> Last update:<strong> {{ subject.update_at }}</strong></p>
        </div>
      </div>
      </a>
      {% endfor %}

【问题讨论】:

  • 您也需要共享您的urls.py 文件,但通常在您的视图中,您需要过滤您想要的部分并将它们附加到render 调用中,就像您在home 中所做的那样功能。我建议您至少阅读 django 官方教程,直到 tutorial 3,但最好是全部内容
  • 我试着让我用一个例子来解释一下让我假设在主题模型中我为数学、化学、生物学等创建了一些表格,然后我在与数学、酸相关的三角形部分中创建了表格与化学有关,与生物学有关的细胞,以及我想要什么,当我点击数学时,它只显示与相关部分的三角形,而不是全部,我想你理解我的问题,简短而言,主题部分将打开,这是相关的
  • 当我喜欢主页功能时,无论哪个主题相关,它都会显示所有部分
  • 您需要在截面视图的 url 中将截面 id 作为参数,阅读我提到的教程,他们经历了整个事情
  • 请您写下您所说的代码,因为我尝试了所有符合我的要求,是的,我读了谢谢

标签: django django-models django-views django-templates


【解决方案1】:

答案已完全编辑,以考虑到您在要求中所做的修改。

1.型号:

请为外键添加相关名称以提高可读性:

class Section(models.Model):
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='sections')

2。主题页面:

您可以在其中显示与所选主题相关的所有部分。

观点:

你需要第二个参数来知道你应该显示哪个主题:

@login_required
def sections(request, subject_id):

    try: # First, you get the requested subject (if it exists)
        subject = Subject.objects.get(id=subject_id)
    except Subject.DoesNotExist: # Use Django shortcuts to display 404 if necessary
        raise Http404("There is no subject with this id.")

    sections = subject.sections

    return render (request, 'sections.html', {'sections': sections})

模板:

您可以通过在 forloop 中使用 {{section.field}} 来了解访问部分字段:

<ul>
    {% for section in sections %}
    <li class="sub"> 
        <a name='thumb' class="thumb" href="#">
            <span><strong> {{ section.title }} </strong> </span> 
        </a>
        <p>Name: {{ section.teacher }} </p> 
        {{ section.price }} 
    </li>
    {% endfor %}
</ul>   

3.主页:

观点:

视图可以保持不变:

@login_required
def home(request):
    subject_list = Subject.objects.all()
    return render (request, 'home.html', {'subject_list': subject_list })

模板:

您可以通过提供正确的 url 名称和要显示的部分的 id 来更改 url 标记:

<ul>
    {% for subject in subject_list %}
    <li class="sub"> 
        <a name='thumb' class="thumb" href="{% url 'section' subject.id %}">
            <img class="thumbnail"  src="{{ subject.thumbnail.url }}" alt=""> 
            <span><strong> {{ subject.name }} </strong> </span> 
        </a>
        <p>No of Section : {{ subject.total_section }} </p> 
    </li>
    {% endfor %}
</ul>

4.网址:

您必须添加我们用于该部分的新参数:

urlpatterns = [
    path('', views.my_login, name='login'),
    path('section/<int:subject_id>/', views.sections, name='section'),
]

这应该可行。

【讨论】:

  • 显示错误 Reverse for 'section' with arguments '('',)' not found。尝试了 1 种模式:['section/(?P[0-9]+)/$']
  • @Shreyash 检查 subject.section 是否为 None,这意味着您在创建该部分时忘记将其绑定到主题。如果不是,请发布生成的 URL。
  • 按您的要求添加
  • @Shreyash 我可能不够清楚,但我只是在谈论生成的 URL。用浏览器进入页面,右键点击链接,点击“复制地址链接”按钮。
  • @Shreyash 我编辑了答案以添加第四步。你能关注它并分享你控制台中打印的内容吗?
【解决方案2】:

在您的models.py 中,将Section 类中的subject 更改为包含related_name 属性

class Section(models.Model):
    subject = models.ForeignKey(Subject, related_name="section" on_delete=models.CASCADE)
    # .... the rest of your fields

然后在视图中编辑您的sections

from django.shortcuts import get_object_or_404

@login_required
def sections(request, subject_id):
    subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject 
    section_list = subject.section.all() # get the sections related to the subject
    print(section_list) 
    return render (request, 'sections.html',{"section_list" : section_list})

并在您的urls.py 中将此添加为urlpatterns 之一

path('section/<int:subject_id>/', views.sections, name='section'),

至于你的home.html

<ul>
    {% for subject in subject_list %}
    <li> 
      <a href="{% url 'section' subject.id %}">
        <img class="thumbnail"  src="{{ subject.thumbnail.url }}" alt=""> 
          <span><strong> {{ subject.name }} </strong> </span> 
      </a>
          <p>No of Section : {{ subject.total_section }} </p> 
    </li>
      {% endfor %}
</ul>

还有你的sections.html

<ul>
    {% for section in section_list %}
        <li> {{ section.title }} </li>
    {$ endfor %}
</ul>

【讨论】:

  • 它显示错误 Reverse for 'section' with arguments '('',)' not found。尝试了 1 种模式:['section/(?P[0-9]+)/$']
  • 三一在我的项目中第二一在我的帐户应用中,第三一在我的主题应用中,但为什么重要
  • 我的错,应该是home.html中的subject.id,我编辑了
  • 点击主题墨水后显示错误
  • AttributeError at /section/3/ 'Subject' 对象没有属性 'section_set'
猜你喜欢
  • 2020-08-09
  • 2018-02-14
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
相关资源
最近更新 更多