自动完成选择和外键

时间:2018-09-26 21:22:47

标签: python django

我是django的初学者,目前正在开发记录出生的应用程序 出生类别的父亲键指向记录父亲和母亲的注册表

在我的form.py文件中,父亲字段是一个自动选择字段。 那就是我的问题: 自动选择字段返回一个ID,而父字段必须指向注册类型的对象

我如何返回链接到ID的对象。 只要父亲字段没有指向某个对象,我就无法在基础中注册新出生

提前谢谢

我的view.py

class EntityCreateView(CreateView):

def form_invalid(self, form, error_msg="Erreur lors de la sauvegarde."):
    messages.error(self.request, self.request.POST)
    return super(EntityCreateView, self).form_invalid(form)

def form_valid(self, form, success_msg="Enregistrement réussi."):
            # This method is called when valid form data has been POSTed.
            # It should return an HttpResponse.
            form.instance.created_by = self.request.user
            messages.success(self.request, success_msg)
            #father_id = form.cleaned_data['father']
            form.father = Registration.objects.get(id=form.father)
            return super(EntityCreateView, self).form_valid(form)

class BirthCreateView(EntityCreateView):
    template_name = 'eregister/birth_detail.html'
    model = Birth
    form_class = BirthForm

    def get_initial(self):
            if 'from_external_page' in self.kwargs and 'birth_post_form' in self.request.POST:
                    # If we added a birth or a person, we want to restore the initial form
                    birth_post_form = self.request.session['birth_post_form']
                    del self.request.session['birth_post_form']
                    return birth_post_form
            return super().get_initial()


    def get_context_data(self, **kwargs):
            """Called after the get method"""
            # Call the base implementation first to get a context
            context = super(BirthCreateView, self).get_context_data(**kwargs)
            birth_form = context.get('form')
            birth_form.initial['language'] = Language.get_default_language()
            return context

    def form_valid(self, form):
            #self.father = Registration.objects.get(father_id=form.father)
            father_id=self.cleaned_data['father']
            father = get_object_or_404(Registration, pk = father_id)
            sel.cleaned_data['father'].update(father)
            super(BirthCreateView, self).form_valid(form)
            birth_id = self.object.id
            # Automatically propose to create the first copy of the book
            return HttpResponseRedirect(reverse('eregister:bc_add', args=[birth_id]))

forms.py文件

 class CommonForm(forms.ModelForm):
required_css_class = 'required'

 class BirthForm(CommonForm):

    class Meta:
            model = Birth
            exclude = ['social_number', 'created']

    firstname = forms.CharField(label=Meta.model._meta.get_field('firstname').verbose_name,
            widget = forms.TextInput(attrs={'size': '50'}))

    father = AutoCompleteSelectField('father_list', label=Meta.model._meta.get_field('father').verbose_name,
            required=False, help_text=None, plugin_options={'autofocus': True, 'minlength': 3})

    mother =  AutoCompleteSelectField('mother_list', label=Meta.model._meta.get_field('mother').verbose_name,
            required=False, help_text=None, plugin_options={'autofocus': True, 'minlength': 3})

    sex = forms.ChoiceField(widget = forms.RadioSelect,choices= SEX_CHOICES)
    birthday = forms.DateField(initial=datetime.date.today())


    def clean_fathers(self):
            if self.cleaned_data['father']:  # It is a list
                    raise forms.ValidationError(_("Please select at least one author"))
            return self.cleaned_data['father']

    def clean_mothers(self):
            if not any(self.cleaned_data['mother']):  # It is a list
                    raise forms.ValidationError(_("Please select at least one publisher"))
            return self.cleaned_data['mother']

models.py

  class Birth(ModelEntity):

    firstname       = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex             = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthweight     = models.DecimalField(max_digits=4,  decimal_places=2, verbose_name="Poids à la naissance")
    birthday        = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour       = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity       = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry    = models.CharField(max_length=50, verbose_name='Pays de naissance', default='Bénin')
    father          = models.ForeignKey(Registration, related_name='father', verbose_name='Father',
                            on_delete=models.CASCADE, null=False)
    mother          = models.ForeignKey(Registration, related_name='mother', verbose_name='Mother',
                            on_delete=models.CASCADE, null=False)
    mairie          = models.CharField(max_length=30, null=False, verbose_name='Mairie')
    social_number   = models.CharField(max_length=30, null=True, verbose_name='numero social', unique=True)
    created         = models.DateTimeField(auto_now_add=True)


    objects = BirthManager()


    def __str__(self):
            return "%s - %s - %s - %s %s - %s - %s" % (self.firstname, self.sex, self.birthweight, self.birthday,
                                                    self.birthhour,self.birthcity, self.birthcountry)

    class Meta:
            ordering = ['-created']
            verbose_name= ("Naissance")
            verbose_name_plural = ("Naissances")

0 个答案:

没有答案