【问题标题】:Transferring user input from one page to another将用户输入从一个页面转移到另一个页面
【发布时间】:2022-06-27 00:15:31
【问题描述】:

我正在制作一个网站,让学生可以为他们的课程找到即将到来的学习课程。我在 Django 和 HTML 中这样做。学生将他们的课程上传到该站点,它们在课程页面上显示为按钮(例如 CS 101 - CS 简介)。当学生点击他们的一门课程(按钮)时,应该会将他们带到一个页面,该页面显示该课程的可用学习课程。我被卡住了,因为我不知道如何根据单击的课程正确过滤下一页上的可用学习课程。有没有办法将课程信息存储为变量,以便在单击按钮时我可以使用该变量来过滤结果? 编辑:我已经进行了这些更改,现在我得到一个 ValueError 太多值,无法解压预期的 2。我几乎可以肯定它正在我的视图中发生。

这是显示用户课程的页面:

<div class="container h-100" style="top:50%; bottom:50%; width:100%;">
  <div class="row">
    {% if courses_list %}
    {% for course in courses_list %}
    <a type="button" class="btn btn-outline-secondary" href="{% url 'study:course-session'%}" >{{ course.subject }} {{ course.number}}-{{course.name}} </a>
    <br><br><br>
    {% endfor %}
    {% else %}
    <p class="text-center">You have not added any courses yet!</p>
    {% endif %}

  </div>
</div>

这是我试图过滤学习课程列表的页面(其中有一个实地课程是课程模型的外键):

     <h1><center>Upcoming Study Sessions</center></h1>

<div>
    <a class="btn btn-success" style="position:absolute; margin-right:2px; top:15%; right:0;" href="{% url 'study:courses' %}" role="button" >Back to My Courses</a>
  
  
</div>
<br><br>

<div class="container h-100" style="top:50%; bottom:50%; width:100%;">
    <div class="row">
      <button type="button" class="btn btn-outline-secondary" >Date/Time: {{ session.date }} <br> Location: {{ session.location }} </button>
      <br><br><br>
  
    </div>
</div>

模板视图:

def CourseSessionView(request, course_pk):

course_wanted = Course.objects.get(id=course_pk)
try:
    return Study.objects.filter(course=course_wanted)
except:
    return messages.error(request, 'There are no upcoming study sessions at this time for the requested course.')

课程和会话模型:

class Course(models.Model):
    SUBJECT_CHOICES = [
        ('AAS', 'AAS')
    ]
    subject = models.CharField(
        max_length=4, choices=SUBJECT_CHOICES, default='')
    number = models.PositiveSmallIntegerField(
        validators=[MaxValueValidator(9999)], default=0)
    name = models.CharField(max_length=100, default='')
    roster = models.ManyToManyField(
        Student, blank=True, related_name="courses")
    # Use [Student object].courses.all() to see all of a student's courses

    def __str__(self):
        return f"{self.subject} {self.number} - {self.name}"


class Study(models.Model):
    organizer = models.ForeignKey(Student, on_delete=models.CASCADE)
    date = models.DateTimeField()
    # Use [Student object].studies.all() to see all of a student's study sessions
    attendees = models.ManyToManyField(Student, related_name="studies")
    location = models.CharField(max_length=30)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.date} - {self.location}"

网址:

path('<int:course_pk>/sessions/',
         views.CourseSessionView, name='course-session')

【问题讨论】:

  • 这个错误完全有道理,你是returning直接在你的try-except块中查询集,在你的CourseSessionView中,请将查询集存储在变量中,然后在try-except块之后,将其作为上下文返回并呈现 html 模板,例如 return render(request,"appname/anyfile.html", context)。并且请基于函数的视图不需要名称在 PascalCase 中,它应该在 snake_case 中。 PascalCase 用于基于类的视图。
  • 您好,感谢您帮助我解决问题。我理解您所说的关于名称格式的内容,这正是教授希望我们对视图进行格式设置的方式,所以我想站在他们好的一边。

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


【解决方案1】:

这将是一种非常笼统的答案,因为您没有提供模型或视图,但我认为想法如下。

首先,在您的模板中,您可以在 url 中传递课程编号的参数:

your_template.html

<a class="btn btn-outline-secondary" 
   href="{% url 'study:course-session' course.pk %}">
   {{ course.subject }} {{ course.number}}-{{course.name}}
</a>

然后在您的视图中,您可以访问该值,并从中获取课程:

views.py

def the_view_name(request, course_pk):
    # Here you now have access to the course's primary key, pk, so you can get the 
    # course and filter the study sessions by that course, etc...

您需要修改 urls.py 以便视图可以接受这个新参数:

urls.py

path('the_view_name/<int:course_pk>', views.the_view_name, name='the_view_name'),

编辑
进行以下更改:
首先到你的views.py:

def CourseSessionView(request, course_pk):

    try:
        course_wanted = Course.objects.get(id=course_pk)
    except:
        return messages.error(request, 'course not found')

    study_sessions = Study.objects.filter(course=course_wanted)

    if study_sessions.count() < 1:
        return messages.error(request, 'There are no upcoming study sessions at this time for the requested course')

    context = {
        'study_sessions': study_sessions,
    }

    return render(request, 'study/your_template_file.html', context)

然后在你的html中

<h1><center>Upcoming Study Sessions</center></h1>

<div>
<a class="btn btn-success" style="position:absolute; margin-right:2px; top:15%; right:0;" href="{% url 'study:courses' %}" role="button" >Back to My Courses</a>

</div>
<br><br>

<div class="container h-100" style="top:50%; bottom:50%; width:100%;">

  {% for session in study_sessions %}
  <div class="row">
   <button type="button" class="btn btn-outline-secondary" >Date/Time: {{ session.date }} <br> Location: {{ session.location }} </button>
   <br><br><br>
  </div>
  {% endfor %}
  
</div>

【讨论】:

  • 您好,我做了类似于您建议的更改,但现在我收到 ValueError too many values to unpack expected 2.
  • @Alex,查看我编辑的答案。
【解决方案2】:

Note: 基于函数的视图的名称不需要像您的情况那样在 PascalCase 中,它应该在 snake_case 中。

显示用户课程的页面,你需要pk的课程:


<div class="container h-100" style="top:50%; bottom:50%; width:100%;">
  <div class="row">
    {% if courses_list %}
    {% for course in courses_list %}
    <a type="button" class="btn btn-outline-secondary" href="{% url 'study:course-session' course.pk %}" >{{ course.subject }} {{ course.number}}-{{course.name}} </a>
    <br><br><br>
    {% endfor %}
    {% else %}
    <p class="text-center">You have not added any courses yet!</p>
    {% endif %}

  </div>
</div>

您对模板的看法,我在snake_case 中定义它,因为它是推荐的方式。

def course_session(request, course_pk):
    course_wanted = Course.objects.get(id=course_pk)
    study_courses=''
    try:
        study_courses= Study.objects.filter(course=course_wanted)
    except:
        messages.error(request, 'There are no upcoming study sessions at this time for the requested course.')
    else:
        return render(request,'anyfolder/anyfile.html',{'study_courses':study_courses})
    
    return render(request,'anyfolder/anyfile.html') #then it will show only your error message.

你在 urls.py 中的url 是这样的:

path('any_route_name/<int:course_pk>/', views.course_session, name='course_session')

Note: 永远不要忘记在urlroute_name 的末尾传递/

然后,在您的任何template 文件中,您可以访问它并运行循环:

{% for study in study_courses %}
{{study.organizer}},{{study.date}}
{% endfor %}

然后,您可以访问其所有属性,并利用ManyToOne 关系。

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 1970-01-01
    • 2017-03-02
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多