具有唯一字段的django更新视图

django update view with unique field

我正在尝试更新表单中的 phone 号码。 两个问题:

  1. 这是一个独特的字段,当我尝试使用相同的 phone 编号更新它时,出现错误(该编号已存在)
  2. 当我保存表单时,它试图清空所有其他字段!

型号:

class Participant(models.Model):
    mobile_number = PhoneNumberField(_("Mobile"), null=True, blank=True, unique=True)

形式:

class EnterMobileForm(forms.ModelForm):

    class Meta:
        model = models.Participant
        fields = ('mobile_number',) 

    def __init__(self, *args, **kwargs):
        participant=kwargs.pop('instance', None)
        super(EnterMobileForm, self).__init__(*args, **kwargs)

        self.fields["mobile_number"].required = True
        if participant.mobile_number:
            self.fields["mobile_number"].initial=participant.mobile_number

查看:

class EnterMobileView(ParticipantLoginRequiredMixin, UpdateView):
    model=models.Participant
    form_class = forms.EnterMobileForm
    template_name = 'participants/enter_mobile.html'
    success_url = reverse_lazy('participants:validate_mobile')


    def get_object(self, queryset=None):
        return get_object_or_404(self.model, pk=self.request.user.participant_set.get().pk)

    def get_form(self, form_class):
        return form_class(instance=self.get_object(), data=self.request.POST or None)


    def get(self, request, *args, **kwargs):
        participant=self.get_object()

        if participant.mobile_verified is not None or participant.nb_times_phone_checked>3:
            return redirect('participants:home')

        participant.nb_times_phone_checked+=1
        participant.save()
        return render(request, self.template_name, {'form': self.get_form(self.form_class)})

当实例化表单时,您已经明确地从 kwargs 字典中弹出 instance 值,因此超类不知道您有一个现有实例。不要那样做。

事实上,您根本不需要任何 __init__ 方法。显示来自实例的初始数据是 ModelForms 已经做的;此处无需覆盖任何内容。