我想建立一个系统,当学生选择某门课程时,只有该所选课程的价格和持续时间才能在为学生添加价格和持续时间的同时动态显示。在添加学生表格中,我想动态生成价格和持续时间所选课程。我该如何实现
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
slug = AutoSlugField(populate_from='title')
basic_price = models.CharField(max_length=50)
advanced_price = models.CharField(max_length=50)
basic_duration = models.CharField(max_length=100)
advanced_duration = models.CharField(max_length=100)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = 'Add Courses Details'
class Student(models.Model):
name = models.CharField(max_length=200)
slug = AutoSlugField(populate_from='name')
phone = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=200)
course = models.ManyToManyField(Course)
# i want price and duration generated dynamically linked to that selected course while adding through form
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Add Student Details'
forms.py
class AddStudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
class AddCourseForm(forms.ModelForm):
class Meta:
model = Course
fields = '__all__'
views.py
def addstudent(request):
if request.method == 'POST':
form = AddStudentForm(request.POST)
if form.is_valid():
student = form.save(commit=False)
student.save()
student.course.set() # i am getting error here also
return redirect('/student/view/student/')
else:
form = AddStudentForm()
return render(request,'student/add_student.html',{'form':form})
def addcourse(request):
if request.method == 'POST':
form = AddCourseForm(request.POST)
if form.is_valid():
course = form.save(commit=False)
course.save()
return redirect('/course/view/course/')
else:
form = AddCourseForm()
return render(request, 'student/add_course.html', {'form': form})
add_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" >
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-success text-center w-100 mb-3" value="Add">
</form>
</body>
</html>
答案 0 :(得分:0)
您需要添加的是many-to-many field-学生可以参加多门课程,一门课程可以包含多名学生。
它的显示和计算方式取决于您的观点。
更新:
好的,我没有真正地对您的模型进行适当的审查。没有代码,关于如何显示的问题就很广泛了,但要点是:
CharField
吗?因为它们基本上是数字,所以很容易将它们设置为纯IntegerField
或FloatField
。ForeignKey
太多了,而价格和期限却很简单。这些字段应另存为纯IntegerField
/ FloatField
,或从链接的课程列表中动态生成。# Get student instance
student = Student.objects.get(pk=1)
# Get all courses for that student
courses = student.courses.all()
# Get sum of basic_price for all of that courses
sum_price = courses.aggregate(Sum('basic_price'))