rom
rom

Reputation: 3672

django update view with unique field

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. When I save the form, it tries to blank all the other fields!

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

Upvotes: 0

Views: 793

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599600

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.

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.

Upvotes: 2

Related Questions