I have a class which has an IntegerField
attr.
In its ModelForm
, in the field of this attr, I need to send a String, which later will store an Integer once it is processed in the view.
The problem is that Django doesn't allows this, and when I use form.cleaned_data.get('myattr')
it's saying that it's wrong because it should be an Integer.
class Student(models.Model):
teacher = models.IntegerField(null=False) # I'm saving teacher's key here
class Teacher(models.Model:
name = models.CharField(max_length= 50, null=False)
key = models.IntegerField(null=False)
class StudentForm(forms.ModelForm):
teacher = forms.ModelChoiceField(queryset=Teacher.objects.all(), label='Select the teacher')
So, when the user is selecting the student's teacher, that select field will display the name of the teachers available. But in the model it will store their key, which I manage in view.
views.py:
teacher = form.cleaned_data.get('teacher') # it has the name
teacher = Teacher.objects.get(name=teacher).key # getting the key in order to store an Integer, but Django is banning my code before anyway.
How can I handle this without changing the data type of the model?
I even added to_field_name
in the form field with the value of the Teachers' key.
答案 0 :(得分:2)
One better approach here will be to setup a relationship between your student and teacher(using foregin key).
Depending of the need of your app here is how to do:
If one student can have several teachers and one teacher can have several students : https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/
If one student can have only one teacher but a teacher can have multiple students: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/
If one student can only have one teacher, and one teacher can only have one student: https://docs.djangoproject.com/en/2.1/topics/db/examples/one_to_one/
This is the best way to manage this. Then you only have to map the Student model in the Student form like:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
#you can add the list of all the fields you want there
fields = ['teacher']
One extra step will be to define the str method of the model so Django will associate a string representation of your model in your form (Here for having a nice way to display Teacher in the student form).
class Teacher(models.Model):
name = models.CharField(max_length= 50, null=False)
#place other fields here ...
def __str__(self):
#if you print a Teacher django will return the string corresponding to the teacher name
return self.name