简体   繁体   中英

How to store current User in Django model

I'm working on an app designed for doctors ( based on django built-in User model) which tracks treatment progress of relevant patients. I've created a Patient model which stores basic data (name,surname,etc.) but it should also store a ForeignKey to the doctor whom is treating this particular patient. I basically want that each doctor can see only own patients and not patients of other doctors. This should be done seamlessly in a form where a logged-in doctor fills-in data of a new patient. And althought the database of Patients is common each doctor should be able to have a patient's name already used by another doctor.

Here's my simplified Patient model:

class Patient(models.Model):
     first_name = models.CharField()
     second_name = models.CharField()
     doctor = models.ForeignKey(User,default="", blank=True, null=True)

     class Meta:
         unique_together=('first_name','second_name','doctor')

The form which should enable to save first and second name without showing the 'doctor' field since this should be added by the form to match the currently logged-in User

class PatientForm(models.Model):
     first_name=forms.CharField(widget=TextInput())
     last_name=forms.CharField(widget=TextInput())

def __init__(self,user,*args, **kwargs):
    super(PatientForm,self).__init__(*args,**kwargs)
    self.user = user

     class Meta:
          model=Patient
          exclude = ['doctor']

And here's the view which ensures that the currently logged-in doctor is saved in the model's 'doctor' ForeignKey.

@login_required
def patient_new(request):
    if request.method == 'POST':
        form = PatientForm(user=request.user,data=request.POST)
        if form.is_valid():
            bbb=form.save(commit=False)
            bbb.doctor = request.user
            bbb.save()
            return HttpResponseRedirect(reverse('patient'))
        else: 
           print form.errors
    else:
            form = PacjentForm(user=request.user)
return render_to_response('patient_new.html',{'form':form}, context_instance=RequestContext(request))

The problem however is that this solution does not allow to have the same Patient name assigned to different doctors (basically the requirement unique_together is never fullfilled). What would be the right way to do that ?

By looking through other solutions I ended-up at this solution, which basically ensures that the User is passed to the form and that the form is verifying whether the patient is unique for this particular doctor. The model stayed untouched, I've changed the form:

class PatientForm(forms.modelForm):
    first_name=forms.CharField(widget=TextInput())
    last_name=forms.CharField(widget=TextInput())

    def __init__(self,user,*args, **kwargs):
         self.request = kwargs.pop('request')            
         return super(PatientForm,self).__init__(*args,**kwargs)

    def clean(self):
         cleaned_data=self.cleaned_data
         try:
             Patient.objects.get(first_name=cleaned_data['first_name'], last_name=cleaned_data['last_name'],doctor=self.request.user)
         except Patient.DoesNotExist:
             pass
         else:
             raise ValidationError('A Patient with this name already exists')

    def save(self,*args, **kwargs):
         kwargs['commit']=False
         obj = super(PatientForm.self).save(*args,**kwargs)
         if self.request:
               obj.doctor = self.request.user
         obj.save()

    class Meta:
        model=Patient
        exclude = ['doctor']

And the view.py changes:

@login_required
def patient_new(request):
    if request.method == 'POST':
        form = PatientForm(request.POST,request=request)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('patient'))
        else: 
            print form.errors
     else:
        form = PacjentForm(request=request)
return render_to_response('patient_new.html',{'form':form}, context_instance=RequestContext(request))

Hope that helps others!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM