Thank you for answer.
I have this error when I try save data for SkladForm, when I press submit
Request Method: POST
Request URL: http://192.168.0.249:8000/sklad
Django Version: 3.0.5
Exception Type: KeyError
Exception Value:
'pack_form'
Exception Location: /var/workspace/myp4/webprint/print/views.py in
form_valid, line 362
line 362 is pack_form = context['pack_form']
And the PackForm is empty, when I call it.
class SkladCreateView(LoginRequiredMixin, CustomSuccessMessageMixin,
CreateView):
model = Sklad
template_name = 'sklad.html'
form_class = SkladForm
success_url = reverse_lazy('sklad')
success_msg = 'Материал сохранён'
def get_context_data(self, **kwargs):
context = super(SkladCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['pack_form'] = PackForm(self.request.POST)
else:
context['pack_form'] = PackForm()
return super().get_context_data(**kwargs)
kwargs['list_sklad'] = Sklad.objects.all().order_by('material')
kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
return super().get_context_data(**kwargs)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.author = self.request.user
self.object.save()
context = self.get_context_data()
pack_form = context['pack_form']
if pack_form.is_valid():
pack_form.instance = self.object
pack_form.save()
return super().form_valid(form)
вторник, 5 мая 2020 г., 11:30:57 UTC+2 пользователь Sherif Adigun написал:
>
> Try this code. Instead of using kwargs[], context is most common.
>
>
> class SkladCreateView(LoginRequiredMixin, CustomSuccessMessageMixin,
> CreateView):
> model = Sklad
> template_name = 'sklad.html'
> form_class = SkladForm
> success_url = reverse_lazy('sklad')
> success_msg = 'Материал сохранён'
>
> def get_context_data(self, **kwargs):
> #kwargs['sklad_form'] = SkladForm # you do not need this anymore since
> you have set the form_class above.
> context = super(SkladCreateView, self).get_context_data(**kwargs)
> if self.request.POST:
> context['pack_form'] = PackForm(self.request.POST)
> else:
> context['pack_form'] = PackForm()
> return super().get_context_data(**kwargs)
>
> def form_valid(self, form):
> self.object = form.save(commit=False)
> self.object.author = self.request.user
> self.object.save()
> context = self.get_context_data()
> pack_form = context['pack_form']
> if pack_form.is_valid():
> pack_form.instance = self.object
> pack_form.save()
> return super().form_valid(form)
>
>
>
>
>
>
>
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/6a47b1be-e884-498e-817f-c91771de4ee2%40googlegroups.com.