我正在尝试更新表单中的电话号码。 两个问题:
型号:
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)})
答案 0 :(得分:2)
在实例化表单时,您已明确地从kwargs dict中弹出instance
值,因此超类不知道您有现有实例。别这么做。
事实上,您根本不需要任何__init__
方法。显示实例的初始数据是ModelForms已经做的事情;这里没有必要覆盖任何东西。