In the django project I was working on, there are classes named Course
and Assignment
. Assignment
is related to Course
by foreignkey
as shown here:
class Assignment(models.Model):
course = models.ForeignKey(Course, related_name='get_assignments')
So every course has few assignments. To create assignments in a course, form named AssignmentForm
is used. In the assignment form, while validating it, in a function, I want to get the name of Course
in which assignment is created. How should I get that?
This is what I've done:
def clean_bulk_add(self):
assig1 = self.cleaned_data['name']
course1 = self.this_course
user1 = course1.owner
tot1 = 30 + len(str(user1)) + len(str(course1.title)) + len(str(assig1)) + len(str(self.cleaned_data['bulk_add']))
if tot1 > 7 :
raise forms.ValidationError("Assignment or Course name is too long: "+str(tot1))
return self.cleaned_data['bulk_add']
You should have something like this,
class AssignmentForm(forms.ModelForm):
class Meta:
model = Assignment
fields = ['course']
def clean_course(self):
course = self.cleaned_data['course']
course_name = course.name
# do some validation on course_name
return 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.