I am working on getting a website up and running with 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. Currently the href is using the views 'assignment_page' function instead of the 'course_page' function.
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. 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.
Here is the html template: This the the course link I discussed
{% 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.
Here are the relevant urls from 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'
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
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. 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().
Any help would be appreciated, sorry for the long post
EDIT: Here is the entire urls.py in the app:
"""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:
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'),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.