django使用唯一字段更新视图

时间:2021-05-20 17:04:06

I am trying to update a phone number in a form. Two problems:

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

  1. It's a unique field and when I try to update it with the same phone number I get an error (this number already exists)
  2. 这是一个独特的领域,当我尝试使用相同的电话号码更新它时,我收到一个错误(此号码已存在)

  3. When I save the form, it tries to blank all the other fields!
  4. 当我保存表单时,它会尝试清除所有其他字段!

Model:

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

Form:

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

View:

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)})

1 个解决方案

#1


You've explicitly popped the instance value from the kwargs dict when the form is instantiated, so the superclass doesn't know that you have an existing instance. Don't do that.

在实例化表单时,您已显式地从kwargs dict弹出实例值,因此超类不知道您有现有实例。不要那样做。

In fact, you don't need any of that __init__ method at all. Displaying initial data from an instance is what ModelForms already do; there is no need to override anything here.

实际上,您根本不需要任何__init__方法。显示实例的初始数据是ModelForms已经做的事情;这里没有必要覆盖任何东西。

#1


You've explicitly popped the instance value from the kwargs dict when the form is instantiated, so the superclass doesn't know that you have an existing instance. Don't do that.

在实例化表单时,您已显式地从kwargs dict弹出实例值,因此超类不知道您有现有实例。不要那样做。

In fact, you don't need any of that __init__ method at all. Displaying initial data from an instance is what ModelForms already do; there is no need to override anything here.

实际上,您根本不需要任何__init__方法。显示实例的初始数据是ModelForms已经做的事情;这里没有必要覆盖任何东西。