因此,我基本上有一个称为Designations的模型,该模型从其他3个模型(课程,角色和职员)中派生外键,并且我试图将新记录保存到Designations模型中,下面的代码显示了Designations and Staffs模型。
class Designations(models.Model):
designation_id = models.AutoField(primary_key=True)
curriculum = models.ForeignKey(Curricula, on_delete=models.CASCADE)
role = models.ForeignKey(Roles, on_delete=models.CASCADE)
staff = models.ForeignKey(Staffs, on_delete=models.CASCADE)
class Meta:
db_table = "arc_designations"
unique_together = ('curriculum', 'role', 'staff')
verbose_name_plural = "Designations"
ordering = ['designation_id']
def __str__(self):
return '%s of %s %s (%s)' % (self.role.role_name,
self.curriculum.course_period.course.course_abbreviation,
self.curriculum.module_period.module.module_abbreviation,
self.staff.staff_full_name)
class Staffs(models.Model):
staff_id = models.AutoField(primary_key=True)
admission_number = models.CharField(max_length=5,
unique=True,
help_text="Enter 5 digits",
validators=[numeric_only, MinLengthValidator(5)])
staff_full_name = models.CharField(max_length=70,
help_text="Enter staff's full name",
validators=[letters_only])
created_by = UserForeignKey(auto_user_add=True,
editable=False,
related_name="staff_created_by",
db_column="created_by")
created_at = models.DateTimeField(auto_now_add=True,
editable=False)
updated_by = UserForeignKey(auto_user=True,
editable=False,
related_name="staff_updated_by",
db_column="updated_by")
updated_at = models.DateTimeField(auto_now=True,
editable=False)
roles = models.ManyToManyField(Roles, through='Designations')
class Meta:
db_table = "arc_staffs"
verbose_name_plural = "Staffs"
ordering = ['staff_id']
def __str__(self):
return '%s (S%s)' % (self.staff_full_name, self.admission_number)
我已经创建了一个form.py来获取mission_number(在Staffs模型中的字段)
class AssignRolesForm(forms.Form):
admission_no = forms.CharField(max_length=40,
widget=forms.TextInput(
attrs={'class': 'form-control', 'aria-describedby': 'add-btn'}))
这是我的html:
<form action="{% url 'setInstructor' %}" method="POST" role="form">
{% csrf_token %}
<div class="form-group">
<div class="input-group">
{{ form.instructor }}
<span class="input-group-btn">
<button type="submit" class="btn btn-default" id="add-btn">assign</button>
</span>
</div>
</div>
</form>
假设我提交表单时,我希望将在表单中输入的admission_number引用到Staffs模型中,然后将其PK保存到staff字段中,并希望课程表和角色字段引用其PK 1各自的型号。点击“提交”后,我该如何在views.py中编写函数以将记录保存到“指定”模型中
这是我尝试过但未起作用的views.py
@require_POST
def setInstructor(request):
form = AssignRolesForm(request.POST)
if form.is_valid():
staff = Staffs(admission_number=form.cleaned_data['instructor'])
role = Roles(pk=1)
curriculum = Curricula(pk=1)
designation = Designations(staff=staff, role=role, curriculum=curriculum)
designation.save()
return redirect('index')