Django - Как предотвратить пустую запись в административной подчиненной форме? - PullRequest
0 голосов
/ 09 октября 2019

Я новичок в Django и Python, поэтому надеюсь, что вы будете снисходительны. Я прочел и снова прочитал документацию по Django, но на данный момент некоторые концепции все еще очень абстрактны для меня ...

У меня естьбазы данных, и я использую ModelForm, и я пытаюсь настроить эти формы администратора. В настоящее время у меня есть основная форма с подчиненной формой, и обе формы настроены

Я заметил «ненормальное» поведение (нежелательное): даже когда запись не сделанав подчиненной форме пустая запись хранится в таблице, соответствующей подчиненной форме в базе данных, как это предотвратить? Я сравнил с другими формами / подчиненными формами в моем приложении, которые не имели такого поведения, но не могли найти, что не так, потому что код, кажется, тот же самый ... заранее спасибо за вашу помощь

моделей.py:

class SuiviAppuiCommunitaire(SafeDeleteModel):

    _safedelete_policy = SOFT_DELETE_CASCADE
    com_ide = models.AutoField(primary_key=True)
    pat = models.ForeignKey(Participante, verbose_name='Participante', related_name='community',
        on_delete=models.CASCADE)
    com_dat = models.DateField("Date de la demande",null=True,blank=True)
    com_mot = models.IntegerField("Motif", max_length=1,null=True,blank=True)
    com_det = models.CharField("Détails", max_length=255,null=True,blank=True)
    com_com = models.CharField("", max_length=255,null=True,blank=True)
    log = HistoricalRecords()

    class Meta:

        db_table = 'crf_com'
        verbose_name_plural = '5.1-Appuis / Suivis communautaires(COM)'
        ordering = ['pat', 'com_dat','com_ide']

    def __str__(self):

        return f"{self.com_ide} / {self.pat.pat_ide_prn_cse} / {self.com_dat}"

        @property
    def participante(self):

        return self.pat.pat_ide_prn_cse

    participante.fget.short_description = 'Participante'


class InterventionCommunautaire(SafeDeleteModel):

    _safedelete_policy = SOFT_DELETE_CASCADE
    com_int_ide = models.AutoField(primary_key=True)
    com = models.ForeignKey(SuiviAppuiCommunitaire, verbose_name='Suivi / appui communautaire', related_name='interventions',
        on_delete=models.CASCADE)
    com_int_dat = models.DateTimeField("Date", null=True, blank=True)
    com_int_edu = models.ForeignKey(Personnel, verbose_name='Personnel', related_name='communitiInterventions', on_delete=models.PROTECT, null=True, blank=True)
    com_int_typ = models.IntegerField("Type")
    com_int_vue = models.IntegerField("La participante a-t-elle été contactée/vue ?")
    com_int_rea = models.CharField("si oui, intervention réalisées", max_length=255)
    com_int_rdv = models.IntegerField("Avez-vous fixé un nouveau rendez-vous ?")
    com_int_rdv_dat = models.DateTimeField("Si oui, date du prochain rendez-vous", null=True, blank=True)
    com_int_rdv_lie = models.IntegerField("Lieu")
    log = HistoricalRecords()

    class Meta:

        db_table = 'crf_com_int'
        verbose_name_plural = 'Interventions communautaires'
        ordering = ['com_int_dat','com', 'com_int_ide']

    def __str__(self):
        return f"{self.com_int_ide} / {(self.com_int_dat)}"

admin.py

class InterventionCommunautaireFormAdmin(forms.ModelForm):
    """ A class to customised the admin form for community interventions. """

    TYPES = Thesaurus.options_list(52)
    VUES = Thesaurus.options_list(1)
    NOUVEAUX = Thesaurus.options_list(53)
    LIEUX = Thesaurus.options_list(44)
    com_int_dat = forms.DateTimeField(label="Date", required=False)
    com_int_typ = forms.ChoiceField(label="Type", widget=forms.Select, choices=TYPES)
    com_int_rea = forms.CharField(label="si oui, interventions réalisées" , widget=forms.Textarea, required=False)
    com_int_vue = forms.ChoiceField(label="La participante a-t-elle été contactée/vue ?", widget=forms.Select, choices=VUES)
    com_int_rdv = forms.ChoiceField(label="Avez-vous fixé un nouveau rendez-vous ?", widget=forms.Select, choices=NOUVEAUX)
    com_int_rdv_dat = forms.DateTimeField(label="Si oui, date du prochain rendez-vous", required=False)
    com_int_rdv_lie = forms.ChoiceField(label="Lieu", widget=forms.Select, choices=LIEUX)


class InterventionCommunautaireInline(admin.TabularInline):

    model = InterventionCommunautaire
    """pour qu'il n y ait pas systématiquement 3 lignes de sous-formulaire en base pour une fiche suivi communautaire"""
    extra = 1 
    form = InterventionCommunautaireFormAdmin


class SuiviAppuiCommunitaireFormAdmin(forms.ModelForm):
    """ A class to customised the admin form for Community. """

    MOTIFS = Thesaurus.options_list(51)
    com_dat = forms.DateField(label="Date de la demande",required=False)
    com_mot = forms.ChoiceField(label="Motif", widget=forms.Select, choices=MOTIFS,required=False)
    com_det = forms.CharField(label="Détails",required=False)
    com_com = forms.CharField(label="", widget=forms.Textarea,required=False)

class SuiviAppuiCommunitaireAdmin(SimpleHistoryAdmin):

    list_display = ('com_ide','participante', 'com_dat',)
    search_fields = ('participante','com_dat')
    fieldsets = (
        ('SUIVI / APPUI COMMUNAUTAIRE', {
            'classes': ('opened',),
            'fields': ('pat', )
        }),
        ('Demande de suivi / appui communautaire', {
            'classes': ('opened',),
            'fields': (('com_dat','com_mot','com_det',), )
        }),
        ('Problèmes rencontrés par la participante / Commentaires libres', {
            'classes': ('opened',),
            'fields': (('com_com',), )
        }),
    )
    form = SuiviAppuiCommunitaireFormAdmin
    inlines = [
        InterventionCommunautaireInline,
    ]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...