django modelform提交

时间:2018-04-08 08:54:00

标签: django modelform

我正在开发一个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方法中,我正在分配患者ID和 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})

提交表单时,我收到错误 - 患者 - 此字段是必填消息。 我尝试在post方法中映射查询集患者,就像get一样。我收到同样的错误。

0 个答案:

没有答案