Пустое поле в базе данных, но я хочу NULL - PullRequest
1 голос
/ 21 апреля 2020

У меня есть форма с условным полем

моя проблема в том, что пустое поле зарегистрировано вместо NULL в базе данных

2 последних поля обусловлены выбранным значением непосредственно перед (ran_bug)

мои 2 условных поля обязательны для заполнения = ложь (даже если это не нужно, но если я не добавляю требуемый, он не проходит проверку?)

в моих моделях это поля null = True и пусто = True

class Randomisation(models.Model):

    ran_ide = models.AutoField(primary_key=True)
    pay_ide = models.CharField("Patient's country code", max_length=2, null=True, blank=True)
    ran_str_num = models.CharField("Logical numerotation", max_length=2, null=True, blank=True)
    ran_bra = models.CharField("Arm", max_length=1, null=True, blank=True)
    bra_lib = models.CharField("Arm label", max_length=50, null=True, blank=True)
    ran_act = models.IntegerField("Activated line", null=True, blank=True)
    pat = models.CharField("Patient number", max_length=12, unique=True, null=True, blank=True)
    ran_nai = models.IntegerField("Patient birthdate (year)", blank=True)    
    ran_sex = models.IntegerField("Sex", null=True, blank=True)
    ran_st1 = models.IntegerField("Stratification variable 1", blank=True)
    ran_st2 = models.IntegerField("Stratification variable 2", blank=True)
    ran_bug = models.IntegerField("Use of alternative randomization procedure?", null=True, blank=True)
    ran_dem_nom = models.CharField("Name of the person asking for randomization", max_length=12, null=True, blank=True)
    ran_dem_dat = models.DateTimeField("Date of demand", null=True, blank=True)
    ran_log = models.DateTimeField("User", null=True, blank=True)
    ran_dat = models.DateTimeField("Date", null=True, auto_now_add=True, blank=True)

forms.py

class RandomizationEditForm(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        super(RandomizationEditForm, self).__init__(*args, **kwargs)
        self.user_country = request.session.get('user_country')
        self.language = request.session.get('language')
        self.user_site_type = request.session.get('user_site_type')        
        PAYS = Pays.options_list(self.user_country,self.user_site_type,self.language)
        SEXE = [(None,''),(1,'Male'),(2,'Female')]
        STRATE_1 = [(None,''),(1,'strate 1 condition 1'),(2,'strate 1 condition 2')]
        STRATE_2 = [(None,''),(1,'strate 2 condition 1'),(2,'strate 2 condition 2')]
        YES = [(0,''),(1,'Yes'),]

        self.fields["pay_ide"] = forms.ChoiceField(label = "Patient's country code", widget=forms.Select, choices=PAYS, initial = self.user_country, disabled=True)
        self.fields["ran_str_num"] = forms.CharField(label = "Logical numerotation", initial = 1, widget=forms.HiddenInput())
        self.fields["ran_bra"] = forms.CharField(label = "Arm", initial = 1, widget=forms.HiddenInput())
        self.fields["bra_lib"] = forms.CharField(label = "Arm label", initial = 'Hydroxychloroquin', widget=forms.HiddenInput())
        self.fields["ran_act"] = forms.IntegerField(label = "Activated line", widget=forms.HiddenInput(), required = False)
        self.fields["pat"] = forms.CharField(label = "Patient number")
        self.fields["ran_nai"] = forms.IntegerField(label = "Patient birthdate (year)", widget=forms.TextInput)
        self.fields["ran_sex"] = forms.ChoiceField(label = "Sex", widget=forms.Select, choices=SEXE)
        self.fields["ran_st1"] = forms.ChoiceField(label = "Stratification variable 1", widget=forms.Select, choices=STRATE_1)
        self.fields["ran_st2"] = forms.ChoiceField(label = "Stratification variable 2", widget=forms.Select, choices=STRATE_2)
        self.fields["ran_bug"] = forms.ChoiceField(label = "Use of alternative randomization procedure?", widget=forms.Select, choices=YES, required = False) 

        self.fields["ran_dem_nom"] = forms.CharField(label = "User", required = False)
        self.fields["ran_dem_dat"] = forms.DateField(
                label = "Date of demand",
                required = False,
            )
        self.fields['ran_dem_dat'].widget.attrs.update({
            'autocomplete': 'off'
        })

    class Meta:
        model = Randomisation
        fields = ('pay_ide','ran_str_num','ran_bra','bra_lib','ran_act','pat','ran_nai','ran_sex','ran_st1','ran_st2','ran_bug','ran_dem_nom','ran_dem_dat',)

script. js

$(document).ready(function() {

    // masquage certains champs du formulaire au chargement de la page
    $(function(){
        $("#div_id_ran_dem_nom").hide();
        $("#div_id_ran_dem_dat").hide();
    });

    // affichage des champs en fonction de la valeur sélectionnée dans la liste 
    $("#div_id_ran_bug").on("change", function(event){
        console.log($("#id_ran_bug").val())

        if ($("#id_ran_bug").val() == 1 ){
            $("#div_id_ran_dem_nom").show();
            $("#div_id_ran_dem_dat").show();
        }
        else {
            $("#div_id_ran_dem_nom").hide();
            $("#div_id_ran_dem_dat").hide();
        }
    });

});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...