Django: Невозможно присвоить «1»: «Randomisation.pay_ide» должен быть экземпляром «Pays» - PullRequest
0 голосов
/ 29 апреля 2020

Я изменил свои модели. Рандомизация с использованием модели FK on Pays. У меня возникла ошибка при попытке зарегистрировать Рандомизацию

Изначально поле pay_ide в моей RandomizationForm должно быть отключено и инициализировано в стране пользователя.

Я пытаюсь упростить, но не понимаю, как решить проблему ... спасибо за помощь

models.py:

class Pays(SafeDeleteModel):
    """ A class to create a country site instance. """

    _safedelete_policy = SOFT_DELETE_CASCADE
    pay_ide = models.AutoField("Code number", primary_key = True)
    pay_nom_eng = models.CharField("Nom", max_length = 150)
    pay_nom_fra = models.CharField("Nom", max_length = 150)
    pay_abr = models.CharField("Code lettre", max_length = 3)
    pay_ran = models.IntegerField("Randomization opened in the country? (y/n)", default=0, null=True, blank=True)
    pay_hor = models.IntegerField("Time zone position relative to GMT",default=0, null=True, blank=True)
    pay_log = models.CharField("Code lettre", max_length = 50)
    pay_dat = models.DateTimeField("Date of settings")
    log = HistoricalRecords()

    class Meta:

        db_table = 'adm_pay'
        verbose_name_plural = 'Pays'
        ordering = ['pay_nom_fra', 'pay_ide']
        permissions = [
            ('can_manage_randomization','Can activate randomization'),
        ]

    @classmethod
    def options_list(cls,pays,type,language):

        if type == 'International' or type == 'National':
            the_opts_set = Pays.objects.all()
        if type == 'Site':
            the_opts_set = Pays.objects.filter(pay_ide = pays)
        if language == 'en':
            the_opts_list = [(opt.pay_ide, opt.pay_nom_eng) for opt in the_opts_set]
        elif language == 'fr':
            the_opts_list = [(opt.pay_ide, opt.pay_nom_fra) for opt in the_opts_set]
        else:
            the_opts_list = [(opt.pay_ide, opt.pay_nom_eng) for opt in the_opts_set]
        the_opts_list.insert(0, (None, ''))
        return the_opts_list

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)
    pay_ide = models.ForeignKey(Pays, on_delete = models.CASCADE) # related country
    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.CharField("User", max_length=12, null=True, blank=True)
    ran_dat = models.DateTimeField("Date", null=True, auto_now_add=True, blank=True)
    log = HistoricalRecords()

    class Meta:

        db_table = 'crf_ran'
        verbose_name_plural = 'randomized'
        ordering = ['ran_ide']
        permissions = [
            ('can_randomize','Can randomized a patient'),
        ]

    def __str__(self):

        return f"{self.ran_ide}"


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.user_country = Pays.objects.get(pay_ide = 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["pay_ide"] = forms.ChoiceField(label = "Patient's country code", widget=forms.Select, choices=PAYS)
        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 (XXX-000-0000)")
        self.fields['pat'].widget.attrs.update({
            'autocomplete': 'off'
        })
        self.fields["ran_nai"] = forms.IntegerField(label = "Patient birthdate (year)", widget=forms.TextInput)
        self.fields['ran_nai'].widget.attrs.update({
            'autocomplete': 'off'
        })
        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_nom'].widget.attrs.update({
            'autocomplete': 'off'
        })
        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',)

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