Answer the question
In order to leave comments, you need to log in
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')
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
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
redirect(reverse('app:view', kwargs={ 'bar': FooBar })) # Id записывать в kwargs
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question