Reputation: 1785
i hope you can help me with this, i've been trying to make a form that autofills a field using the concatenation of two fields on the same form, but with no success, this is my model and my form
class Doctor(models.Model):
name_doctor = models.CharField(max_length=20)
last_doctor = models.CharField(max_length=20)
email_doctor = models.EmailField()
p_doctor = models.CharField(max_length=10)
id_doctor = models.CharField(max_length=30, blank=True)
def __str__(self):
return '%s %s' % (self.name_doctor, self.last_doctor)
And my form:
class ADoctor(forms.ModelForm):
class Meta:
model = Doctor
fields = ('name_doctor', 'last_doctor', 'email_doctor', 'p_doctor', 'id_doctor')
labels = {
'name_doctor': ('Name'),
'last_doctor': ('Last name'),
'email_doctor': ('Email'),
'p_doctor': ('Phone'),
'id_doctor': ('ID'),
}
How can i override the save so that when i send the form the field id_doctor fills with the concatenation of name_doctor + last_doctor ?
Upvotes: 1
Views: 6433
Reputation: 53734
The answer is: don't bother.
Whenever you can generate some item of data based on the content of one or more fields on the table, you do not need to create another field for it. And your name_doctor
+ last_doctor
is a classic example of this.
Your model already has a name_doctor field as well as a last_doctor field, it's a trivial matter to display them by combining them together. There is no need to save it to the database and you shouldn't.
Edit: You can produce any custom combination of fields by just adding a method to the model example:
class Doctor(models.Model):
def concat_fields(self):
return self.name_doctor + self.last_doctor
def quasi_unique_id(self):
return self.name_doctor[0:2] + self.last_doctor[0:2] + id_order(some_other_model)
Upvotes: 3
Reputation: 1785
SOLVED, i just added this before my post.save on my form def on my views.py
post.id_doctor = form['name_doctor'].value() + form['last_doctor'].value()
post.save()
Upvotes: -1