我有两个使用不同URL访问的更新视图。在第一个更新视图CreateType
中,我在名字的初始位置设置了一个变量old_type
。提交并浏览其他视图后,我将进入第二个UpdateView CreateSchedule
。如果我在第二个视图中打印self.initial,则由于某种原因,我会在第一个UpdateView中找到变量old_type
。
第一视图
class CreateType(views.UpdateView):
"""
Create type form
"""
model = Group
form_class = TypeForm
template_name = 'create.html'
extra_context = {'has_fifth_steps': False, 'active_step': 1, 'progress': 0}
def get_object(self, queryset=None):
object = super(CreateType, self).get_object(queryset)
self.initial['old_type'] = object.type
return object
def form_valid(self, form):
object = form.save()
if object.type == Group.TYPE_SINGLE and self.initial['old_type'] == Group.TYPE_MULTIPLE:
first_obj = Obj.objects.filter(group=object).values('id').first()
if first_obj:
Obj.objects.filter(group=object).exclude(id=first_obj['id']).delete()
return redirect('create_obj.debtor', pk=object.pk)
我的第二个观点:
class CreateSchedule(views.UpdateView):
"""
Schedule form
"""
model = Group
fields = []
template_name = 'createschedule.html'
def get_object(self, queryset=None):
object = super(CreateSchedule, self).get_object(queryset)
# if object.type == Group.TYPE_SINGLE:
self.obj_object = Obj.objects.filter(group=object).first()
return object
def get_form(self, form_class=None):
paymentschedule_formset = modelformset_factory(
model=PaymentSchedule,
form=PaymentScheduleForm,
fields=('due_date', 'value'),
validate_min=True,
min_num=self.obj_object.number_of_payments,
validate_max=True,
max_num=self.obj_object.number_of_payments,
)
print(self.initial)
return paymentschedule_formset(
queryset=PaymentSchedule.objects.filter(obj=self.obj_object),
)
def get_context_data(self, **kwargs):
context = super(CreateSchedule, self).get_context_data(**kwargs)
if self.object.type == Group.TYPE_MULTIPLE:
context['has_fifth_steps'] = True
context['active_step'] = 5
else:
context['has_fifth_steps'] = False
context['active_step'] = 4
context['progress'] = 100
return context
不确定我做错了什么还是这是正常行为,对我来说没有多大意义。
感谢任何帮助!
编辑:
添加了urls.py
urlpatterns = [
path('create/<int:pk>/', sanad.CreateType.as_view(), name='create_obj.type'),
path('create/<int:pk>/payments-schedule', CreatesSchedule.as_view(), name='create_obj.schedule'),
]
答案 0 :(得分:1)
您永远不要修改self.initial
。那是在FormMixin中的类级别定义的字典,CreateView使用该字典。如果您修改该字典,则所有视图都可以看到该修改。
您不应该这样做。无论如何,在get_object
中更改初始名称是错误的事情。而是定义get_initial()
方法以返回包含该值的新字典:
def get_initial(self):
return {'old_type': self.object.type}
现在,您根本不需要覆盖get_object
。