S
S
slmuim2022-01-22 13:11:39
Django
slmuim, 2022-01-22 13:11:39

How to pass a value to a form in Django?

The project has two models: Client and Order. The Order model is linked to the Client model using a ForeignKey.
The task is this:
When creating a client (Records to the Client model), it is necessary that the user be redirected from the client creation page to the order creation page, with the newly created client already selected.

models.py

class Client(models.Model):
    name = models.CharField('ФИО клиента', max_length=100, unique=True)
    phone = models.CharField('Телефон', max_length=9)

class Orders(models.Model):
    client = models.ForeignKey(Client, verbose_name='Клиент', on_delete=models.PROTECT)
    price = models.PositiveIntegerField('Цена', help_text='USD')
    amount = models.PositiveIntegerField('Сумма', help_text='USD')


views.py
class AddClient(LoginRequiredMixin, CreateView):
    form_class = AddClientForm
    template_name = 'clients/add_client.html'
    login_url = reverse_lazy('login')

    def form_valid(self, form):
        form.save()
        return redirect('add_order')

class AddOrder(LoginRequiredMixin, CreateView):
    form_class = AddOrderForm
    template_name = 'clients/add_order.html'
    login_url = reverse_lazy('login')

    def form_valid(self, form):
        form.save()
        return redirect('start')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-01-22
@slmuim

Already wrote, in theory - the mail should be more or less - a complete answer.
Option 1:
Use session.
In AddClient save id to it

client = form.save()
request.session['client_id'] = client.id
request.session.modified = True

In AddOrder, save the form with commit=False and add the id from the session, then remove the key from it (also with ...modified = True)
UPD: You will need to update the model by changing the FK and making it null/blank=True.
Well, check before saving the order, whether there is a necessary key in the session.
Pros: you can continue editing even after creating a user and closing the browser.
Cons: without additional processing (for example, a ban on modifying an existing key in the session), a case may arise when the user is overwritten before creating the order.
Option 2:
redirect(reverse('app:view', kwargs={ 'bar': FooBar })) # Id записывать в kwargs

Pros: the above situation will not arise.
Cons: need to modernize url

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question