Two forms in one template

65 views
Skip to first unread message

Sergei Sokov

unread,
May 4, 2020, 11:37:39 AM5/4/20
to Django users
I have two forms in one template, but one of them doesn't  have data to my database.
Why does it happen and how to fix it?

When I fill out the Pack form and press "submit" the terminal shows that: "POST" /sklad HTTP/1.1" 200 9937
This data doesn't save to my database.

When I fill out the Sklad form and press "submit" the terminal shows that: "POST" /sklad HTTP/1.1" 302 0
This data saves to my database fine.

views.py
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
        kwargs['pack_form'] = PackForm
        kwargs['list_sklad'] = Sklad.objects.all().order_by('material')
        kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
        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()
        return super().form_valid(form)

models.py
class Sklad(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='автор склада', null=True)
material = models.CharField('название', max_length=200)
unit = models.CharField('единица измерения', max_length=200)
description = models.CharField('описание', max_length=200, null=True)
price_buy = models.IntegerField('цена закупки', )
price_sell = models.IntegerField('цена продажи', )
amount = models.IntegerField('количество', default='0')

def __str__(self):
return self.material

class Pack(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='автор упаковки', null=True)
name_pack = models.CharField('название', max_length=100)
price_pack = models.IntegerField('цена', )

def __str__(self):
return self.name_pack


forms.py
class SkladForm(forms.ModelForm):
    class Meta:
        model = Sklad
        fields = (
            'material',
            'unit',
            'description',
            'price_buy',
            'price_sell',
            'amount',
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

class PackForm(forms.ModelForm):
    class Meta:
        model = Pack
        fields = (
            'name_pack',
            'price_pack',
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'


Sherif Adigun

unread,
May 4, 2020, 12:42:10 PM5/4/20
to Django users
Your code is working perfectly. Just that you need to remember that the view has its model set to Sklad. Hence, when you called super() on form_valid, only the Skald instance is saved.

You need to manually save the Pack form in the form_valid method.

Sergei Sokov

unread,
May 4, 2020, 12:54:09 PM5/4/20
to Django users
I guessed about it.
But I dont know how to do that.

понедельник, 4 мая 2020 г., 18:42:10 UTC+2 пользователь Sherif Adigun написал:

Sherif Adigun

unread,
May 5, 2020, 5:30:57 AM5/5/20
to Django users
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)






Sergei Sokov

unread,
May 5, 2020, 10:58:59 AM5/5/20
to Django users
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 написал:

Sherif Adigun

unread,
May 5, 2020, 12:08:56 PM5/5/20
to Django users
you have two returns in get_Context_data. use only this

Sergei Sokov

unread,
May 5, 2020, 3:28:56 PM5/5/20
to Django users
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):
        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')
        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)




вторник, 5 мая 2020 г., 18:08:56 UTC+2 пользователь Sherif Adigun написал:

Sherif Adigun

unread,
May 5, 2020, 4:17:08 PM5/5/20
to django...@googlegroups.com
Please remove 

  if pack_form.is_valid():
            pack_form.instance = self.object
            pack_form.save()


And replace with print(pack_form)


Then let's see what it's printing in the console

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/I_32m8lWd-g/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b3bcc2cc-aa55-42b1-a322-769f177c1862%40googlegroups.com.

Sergei Sokov

unread,
May 6, 2020, 3:12:33 AM5/6/20
to Django users

kwargs.JPG

But the form is empty.

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['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')
        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()
        print(pack_form)
        return super().form_valid(form)



вторник, 5 мая 2020 г., 22:17:08 UTC+2 пользователь Sherif Adigun написал:
To unsubscribe from this group and all its topics, send an email to django...@googlegroups.com.

Sherif Adigun

unread,
May 6, 2020, 4:08:47 AM5/6/20
to django...@googlegroups.com
Can you come to zoom so we fix this ones and for all

To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e6bd5958-e885-488c-85e8-9452589d50cf%40googlegroups.com.

Sergei Sokov

unread,
May 6, 2020, 4:37:42 AM5/6/20
to Django users
I can but my english is very bad.

среда, 6 мая 2020 г., 10:08:47 UTC+2 пользователь Sherif Adigun написал:

Sergei Sokov

unread,
May 6, 2020, 4:38:13 AM5/6/20
to Django users
my zoom
Sergey Sokov

среда, 6 мая 2020 г., 10:37:42 UTC+2 пользователь Sergei Sokov написал:

Sherif Adigun

unread,
May 6, 2020, 6:00:13 AM5/6/20
to Django users
Please join the meeting now let's quickly fix it .

Sergei Sokov

unread,
May 6, 2020, 6:12:50 AM5/6/20
to Django users
I can a little bit later, ok?
I think in 2 hour

среда, 6 мая 2020 г., 12:00:13 UTC+2 пользователь Sherif Adigun написал:

Sherif Adigun

unread,
May 6, 2020, 6:35:28 AM5/6/20
to django...@googlegroups.com
ok. send a reply when you are available.

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/I_32m8lWd-g/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/257e308b-91d3-4fa3-8f8f-ca758b72e7e0%40googlegroups.com.

Sergei Sokov

unread,
May 6, 2020, 8:45:13 AM5/6/20
to Django users
I am ready

среда, 6 мая 2020 г., 12:35:28 UTC+2 пользователь Sherif Adigun написал:
To unsubscribe from this group and all its topics, send an email to django...@googlegroups.com.

Sherif Adigun

unread,
May 6, 2020, 9:09:39 AM5/6/20
to django...@googlegroups.com

Sergei Sokov

unread,
May 6, 2020, 9:43:11 AM5/6/20
to Django users
Thank you very much!!!!!!
You are best!!!

среда, 6 мая 2020 г., 15:09:39 UTC+2 пользователь Sherif Adigun написал:

Sherif Adigun

unread,
May 6, 2020, 9:47:00 AM5/6/20
to django...@googlegroups.com
You are welcome.

I'm happy to help

Sergei Sokov

unread,
Feb 4, 2021, 8:44:54 AM2/4/21
to Django users
Hi, I have same problem.
I am doing same like did you but it doesnt work. POST doesnt work.
Could you please hrlp me with it?

среда, 6 мая 2020 г. в 12:47:00 UTC-1, adigun...@gmail.com:

Siarhei Siarhei

unread,
Feb 4, 2021, 10:13:24 AM2/4/21
to Django users

Sergei Sokov

unread,
Feb 4, 2021, 2:41:16 PM2/4/21
to Django users
Thank you so mach!

четверг, 4 февраля 2021 г. в 14:13:24 UTC-1, wne...@gmail.com:
Reply all
Reply to author
Forward
0 new messages