[Answer]-How not to display the created_by field but auto-populate it with the current user keeping the unique_together rule?

1👍

Django already validates the uniqueness of your model for you, there’s no need to do it yourself. The trick is to make sure the created_by field is set before the model is validated, i.e. if you’re creating a new patient:

p = Patient(created_by=request.user)
form = PatientForm(data=request.POST or None, instance=p)

There’s no need to add the created_by field to the form – unless the current user is just a default value and the doctor can add another doctor’s patients to the system. In both cases, Django itself checks that your Patient follows the unique_together constraints.

👤knbk

Leave a comment