我正在尝试在管理界面中自定义模型的添加按钮。为此,我为此模型编写了一个管理模型,并尝试覆盖add_view
定义。但是我收到了错误
"<modelStudent: Student:>" needs to have a value for field "modelstudent" before this many-to-many relationship can be used.
这是我的模特
class modelStudent(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True)
school = models.ForeignKey(modelSchool)
first_name = models.CharField(max_length=128, unique=False)
这是该模型的管理模型
class modelStudentAdmin(admin.ModelAdmin):
form = adminStudentForm
def get_queryset(self, request):
qs = super(modelStudentAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
schoolInstance = modelSchool.objects.get(user=request.user)
qs = modelStudent.objects.filter(school=schoolInstance)
return qs
def add_view(self, request, form_url='', extra_context=None):
if request.user.is_superuser:
return super(modelStudentAdmin,self).add_view(request,form_url,extra_context)
elif request.method == 'POST':
form = UploadFileForm(request.POST,request.FILES)
if form.is_valid():
email = form.cleaned_data["send_email"]
handle_uploaded_file(request.FILES['file'],request)
return HttpResponseRedirect('/admin/')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
我认为此问题是由于表单分配form = adminStudentForm
这是adminStudentForm
class adminStudentForm(forms.ModelForm):
class Meta:
model = modelStudent
fields = '__all__'
patients = forms.ModelMultipleChoiceField(queryset=modelPatient.objects.all())
def __init__(self, *args, **kwargs):
super(adminStudentForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['patients'].initial = self.instance.modelpatient_set.all()
def save(self, *args, **kwargs):
try:
instance = super(adminStudentForm, self).save(commit=False)
patients_qset = self.cleaned_data['patients']
for pqset in patients_qset:
pqset.student.add(instance)
except Exception as e:
print(e)
raise
return instance
这是modelPatient
class modelPatient(models.Model):
student = models.ManyToManyField(modelStudent,null=True,default=None,blank=True)
patient_name = models.CharField(max_length=128, unique=False)
patient_age = models.IntegerField(default=0)
为什么在此处添加表单会导致问题?关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
也许你把它放在modelStudent下?不确定,但值得一试......
def __str__(self):
return(self.user)