отправка формы модели django

avatar
prakash joy
8 апреля 2018 в 08:53
56
0
2

Я работаю над проектом django. Модель CaseRegister. Я пытаюсь отправить значения, используя форму модели. Мой модельный класс belo

             - model.py

            from django.db import models

            from core.models import ProviderMaster,FacilityMaster,ProviderMaster,CaseMaster,CasestatusMaster  
            from patient.models import PatientMaster   
            from django.contrib.auth.models import User  
            from django.forms import ModelForm  
            from account.models import Profile

            def update_id(func):
               def decorated_function(*args):        
                    data_object = args[0]            
                    sequence_name = 'seq_%s' % data_object._meta.db_table        
                    from django.db import connection
                    cursor = connection.cursor()
                    cursor.execute("SELECT nextval(%s)", [sequence_name])
                    row = cursor.fetchone()        
                    data_object.caseid = row[0]   
                    return func(*args)    
                return decorated_function

            class CaseRegister(models.Model):
                caseid = models.DecimalField(primary_key=True, max_digits=8, decimal_places=0)
                patient = models.ForeignKey(PatientMaster, on_delete=models.CASCADE, db_column='patientid') 
                case_startdate = models.DateField()
                case_enddate = models.DateField(blank=True, null=True)
                providerid = models.ForeignKey(ProviderMaster, models.DO_NOTHING, db_column='providerid', blank=True, null=True)
                facilityid = models.ForeignKey(FacilityMaster, models.DO_NOTHING, db_column='facilityid', blank=True, null=True)
                casetypeid = models.ForeignKey(CaseMaster, models.DO_NOTHING, db_column='casetypeid', blank=True, null=True)
                casestatus = models.ForeignKey(CasestatusMaster, models.DO_NOTHING, db_column='casestatus', blank=True, null=True)    
                approved_date = models.DateField(blank=True, null=True)
                last_modifieduser = models.ForeignKey(Profile,on_delete=models.CASCADE, db_column='last_modifieduser')
                class Meta:
                    managed = False
                    db_table = 'case_register'
                def __str__(self):
                    return self.caseid
                @update_id
                def save(self):
                    # Now actually save the object.
                    super(CaseRegister, self).save()        

Форма создается, как показано ниже, и сопоставленный набор запросов для всех полей FK

     - The form.py

        from django import forms
        from .models import CaseRegister
        from  patient.models import PatientMaster
        from django.contrib.auth.models import User
        from account.models import Profile,ProfileFaciltiyMembership
        from  core.models import FacilityMaster,CasestatusMaster,ProviderMaster,ProviderCategory,RoleMaster
        from django.db.models import Q
        import datetime

        class CaseRegisterForm(forms.ModelForm):
            class Meta:
                model = CaseRegister
                fields = ('caseid', 'patient', 'case_startdate',"case_enddate","facilityid","providerid","casetypeid","casestatus","last_modifieduser" )
            def __init__(self, p,profile,request, *args, **kwargs):
                super(CaseRegisterForm, self).__init__(*args, **kwargs)
                print("request.method   "+request.method)
                if (request.method=='GET'):
                    print("request.method   "+request.method)
                    self.fields['patient'].empty_label = None
                    self.fields['patient'].label="Patient"      
                    self.fields['patient'].queryset = PatientMaster.objects.filter(patientid=p.patientid)               
                    self.fields['patient'].widget.attrs = {'maxlength': 10}
                    self.fields['patient'].widget.attrs = {'disabled': True}

                self.fields['case_startdate'].widget.attrs = {'class': 'vDateField'}
                self.fields['case_startdate'].label="Date"
                self.fields['case_startdate'].initial=datetime.datetime.now().date()

                #self.fields['last_modifieduser'].queryset = Profile.objects.filter(user=profile.user)
                self.fields['last_modifieduser'].queryset = Profile.objects.all()
                self.fields['last_modifieduser'].empty_label = None
                #self.fields['last_modifieduser'].widget = forms.HiddenInput()      
                self.fields['caseid'].required = False      
                self.fields['caseid'].widget = forms.HiddenInput()
                self.fields['case_enddate'].widget = forms.HiddenInput()
                fid =  request.session["currfacility"]      
                self.fields['facilityid'].empty_label = None
                self.fields['facilityid'].queryset = FacilityMaster.objects.filter(facilityid=fid)
                self.fields['facilityid'].widget.attrs = {'disabled': True}
                self.fields['casestatus'].empty_label = None
                self.fields['casestatus'].queryset=CasestatusMaster.objects.filter(casestatusid=1)
                facility=FacilityMaster.objects.get(pk=fid)
                profiles=Profile.objects.filter(facilities=facility)
                providercat = ProviderCategory.objects.get(pk=2)
                self.fields['providerid'].empty_label = None    
                self.fields['providerid'].label="Physician" 
                self.fields['casetypeid'].label="Type"
                self.fields['casetypeid'].empty_label = None    
                self.fields['casestatus'].label="Status"    
                criterion1 = Q(profile__in=profiles)
                criterion2 = Q(pcategoryid=providercat)
                rid = request.session["currrole"]
                print(rid)
                if rid == str(2) :
                    print("if")         
                    profile = request.user.profile
                    pfid = profile.provider.providerid
                    print(pfid)
                    criterion3 = Q(providerid=pfid)
                    self.fields['providerid'].queryset =  ProviderMaster.objects.filter(criterion3 & criterion2)
                else:
                    print("else")
                    self.fields['providerid'].queryset =  ProviderMaster.objects.filter(criterion1 & criterion2)

Ниже показано представление, и в методе GET я назначаю идентификатор пациента и в POST-запрос, я ничего не делаю с формой модели.
- view.py

from django.shortcuts import render,redirect
from .forms import CaseRegisterForm
from .models import CaseRegister
from patient.models import PatientMaster
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView, DetailView, UpdateView


def caseregister(request):
    pid =1413963        
    if request.method == "POST":                
        form = CaseRegisterForm(None,request.user.profile,request,request.POST)                                
        #form = CaseRegisterForm(request.POST)                                
        print(form.is_valid())
        print(form.errors)
        if form.is_valid():                             

            model_instance = form.save(commit=False)            
            model_instance.save()
            return redirect('{% url "createcase" %}')
    else:
        pid =1413963
        p = PatientMaster.objects.get(pk=pid)
        form = CaseRegisterForm(p,request.user.profile,request)        
        return render(request, "case_register.html", {'form': form})

При отправке формы я получаю сообщение об ошибке - пациент. Это поле обязательно для заполнения. Я попытался сопоставить пациента с набором запросов в почтовом методе так же, как и получить. Я получаю ту же ошибку.

Источник

Ответы (0)