简体   繁体   English

为什么我的href标签指向其他功能?

[英]Why is my href tag directing to a different function?

I am working on getting a website up and running with Django 2.2. 我正在使用Django 2.2建立网站并运行。 I am attempting to get a sidebar put together and I figured the first step is make sure I am linking to the right place and then go from there. 我试图将侧边栏放在一起,我认为第一步是确保我链接到正确的位置,然后从那里开始。 On my html template I have links so that students can view assignment details and on the sidebar there should be links so students can go to course pages. 在我的html模板上,我具有链接,以便学生可以查看作业详细信息,并且在侧栏上应该具有链接,以便学生可以转到课程页面。 Currently the href is using the views 'assignment_page' function instead of the 'course_page' function. 目前,href使用的是视图的“ assignment_page”功能而不是“ course_page”功能。

I have researched into what I should be doing inside the anchor href tag and I feel like I am doing it right as the assignment links work. 我已经研究了如何在anchor href标签内进行操作,当分配链接正常工作时,我觉得我做对了。 Looking below you can see the structure of the href tag for the assignment and the course links are the same but the course link doesn't point in the right place. 从下面看,您可以看到作业的href标记的结构,课程链接相同,但课程链接指向的位置不正确。

Here is the html template: This the the course link I discussed 这是html模板:这是我讨论的课程链接

{% for course in student_courses %}
<div>
    <a href="{% url 'view_course' course.title %}"> {{ course.title }} 
    </a>
</div>

{% endfor %}

Here is the assignment link 这是作业链接

{% for assignment in course_assignments %}
<div>
    <a href="{% url 'view_assignment' assignment.title %}"> {{ 
    assignment.title }}</a>
    <p>Due Date: {{ assignment.due_date }}</p>
</div>
{% endfor %}

As you can see, the href points to the path in urls.py with the name 'view_course' for the first one and 'view_assignment' for the second set. 如您所见,href指向urls.py中的路径,第一个名称为'view_course',第二个名称为'view_assignment'。

Here are the relevant urls from urls.py: 以下是urls.py中的相关网址:

path('<assignment_title>/',assignment_page, name='view_assignment'),
path('<course_title>/', course_page, name='view_course'),

So they are named right 所以他们被正确地命名

that means they should call the respective views of 'course_page' and 'assignment_page' 这意味着他们应该分别调用“ course_page”和“ assignment_page”的视图

Here are those views: 这些是这些视图:

def assignment_page(request, assignment_title):
    print('\nAssignment\n')
    current_assignment = Assignment.objects.get(title=assignment_title)
    return render(request, 'assignment.html', 
           {'assignment':current_assignment})

def course_page(request, course_title):
    print('\nCourse\n')
    current_course = Course.objects.get(title=course_title)
    return render(request, 'course.html', {'course':current_course})

I could tell from those print statements that when I clicked on the Course link, it went to the assignment_page function from the view as it printed 从这些打印语句中可以看出,当我单击“课程”链接时,它在打印时从视图转到了assignment_page函数

Assignment 分配

in the server output. 在服务器输出中。

So the expected result is that it should direct to the basic course.html page and not the assignment.html page. 因此,预期结果是应将其定向到基本的course.html页面,而不应定向到assignment.html页面。 The Error I get is saying an assignment of the name of the course, in this case, CS 120, does not exist, that is a course name so that is expected, but it shouldn't be using the Assignment.objects.get(). 我收到的错误是说课程名称的分配,在这种情况下,CS 120不存在,这是课程名称,因此是可以预期的,但不应使用Assignment.objects.get( )。

Any help would be appreciated, sorry for the long post 任何帮助,将不胜感激,很长的帖子

EDIT: Here is the entire urls.py in the app: 编辑:这是应用程序中的整个urls.py:

"""superlists URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
    from django.conf.urls import url, include
    from django.contrib import admin
    from .views import course_page, assignment_page
    from django.urls import path


    urlpatterns = [
    url(r'accounts/', include('django.contrib.auth.urls')),
    path('<assignment_title>/',assignment_page, name='view_assignment'),
    path('<course_title>/', course_page, name='view_course'),
    ]

Here is the entire models.py: 这是整个model.py:

    from django.db import models
    from django import forms
    from django.conf import settings
    from html.parser import HTMLParser
    from django.contrib.auth.models import User
    import string
    import random
    from email.message import EmailMessage
    import smtplib


    def email_password(sender, recipiant, password):
    msg = EmailMessage()
    msg.set_content(password)
    msg['From'] = sender
    msg['To'] = recipiant
    msg['Subject'] = 'Password for Socrates'

    smtp_server = smtplib.SMTP('localhost')
    smtp_server.send_message(msg)
    smtp_server.quit()



    class Student(models.Model):

    name = models.CharField(default = '', max_length = 50)
    email = models.CharField(default = '', max_length = 40)
    number = models.IntegerField(default = '')
    year = models.CharField(default = '', max_length = 19)

    def add_info(self, info):
        self.name_parts = info[3].split()
        self.name = self.name_parts[1] + ' ' + self.name_parts[0][:-1]
        self.email = info[6]
        self.number = int(info[2])
        self.year = info[-1]
        self.save()

    def create_account(self):
        password = self.password_gen(8)
        user = User.objects.create(
            username=self.name_parts[1] + '.' + self.name_parts[0][:-1], 
            password=password, 
            email=self.email,
            first_name=self.name_parts[1],
            last_name=self.name_parts[0][:-1]
            )

    def password_gen(self, size=6, chars=string.ascii_uppercase + 
        string.digits + string.ascii_lowercase):
        return ''.join(random.choice(chars) for _ in range(size))

    def __str__(self):
        return self.name


    class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.data_list = []
        self.tag_list = []

    def handle_data(self, data):
        if data not in ['\t', '\n']:
            self.data_list.append(data)        

    def feed_file(self, file_path):
        ofile = open(file_path, 'r')
        f = ofile.readlines()
        for line in f:
            self.feed(line)

    def print_data(self):
        for student in self.data_list:
            print(student)

    def sort_data_list(self, start_char='\t\t\t', stop_char='\t\t'):
        # Sorts the data list compiling all of the data for each student into 
    sperate lists
        new_data_list = []
        will_append = False
        for entry in self.data_list:
            if entry == start_char:
                will_append = True
                student = []
            elif entry == stop_char:
                if will_append == True:
                    new_data_list.append(student)
                will_append = False
            if will_append and entry is not start_char:
                student.append(entry)
        self.data_list = new_data_list


    class Course(models.Model):

    Class_File = models.FileField(upload_to='class_htmls')
    code = models.CharField(default='', max_length=20, blank=True)
    title = models.CharField(default='', max_length=50, blank=True)
    term = models.CharField(default='', max_length=60, blank=True)
    students = models.ManyToManyField(Student, 
    related_name='enrolled_students')
    course_instructor = models.ForeignKey(settings.AUTH_USER_MODEL, 
    on_delete=models.CASCADE, blank=True, null=True)

    def create(self, file=None):
        if file is None:
            file = self.Class_File.path
        Parser = MyHTMLParser()      
        Parser.feed_file(file)
        Parser.sort_data_list('\t\t\t', '\t\t')
        course_info = Parser.data_list[0][1].split(' | ')
        self.student_info = Parser.data_list[2:]
        self.code = course_info[2]
        self.term = course_info[0][11:]
        self.title = course_info[3][:course_info[3].find(' (')]
        self.save()
        self.add_students()
        self.save()

    def add_students(self):
        students_in_db = Student.objects.all()
        for info in self.student_info:
            student_in_db = students_in_db.filter(number=info[2])
            if student_in_db.count() == 1:
                new_student = student_in_db.first()
            elif student_in_db.count() == 0:
                new_student = Student()
                new_student.add_info(info)
                new_student.create_account()
            self.students.add(new_student)

    def __str__(self):
        return self.title


    class Assignment(models.Model):

    course = models.ForeignKey(Course, on_delete=models.CASCADE, blank=True, 
    null=True)
    title = models.CharField(max_length=50, default='')
    description = models.TextField(default='')
    due_date = models.DateTimeField(blank=True, null=True)
    #assignment_creator = models.CharField(default=request.user)

    def __str__(self):
        return self.title

Spacing is a bit off but here are all the models I use. 间距有些偏离,但是这里是我使用的所有模型。

Update path 更新路径

path('assignment/<assignment_title>/',assignment_page, name='view_assignment'),
path('course/<course_title>/', course_page, name='view_course'),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM