问题
I'd like to use two forms into the same views. It is a restricted channel. The first forms is a chat and the second one launch the conversation (boolean fiels with default = false). All forms share the same success url.
Do you have any ideas? I'm beginning with Django :) Thanks for your help
Here is my views:
@method_decorator(login_required(login_url='/cooker/login'),name="dispatch")
class CheckoutDetail(generic.DetailView, FormMixin):
model = Sugargroup
context_object_name = 'sugargroup'
template_name = 'checkout_detail.html'
form_class = CreateSugarChatForm
validation_form_class = LaunchSugargroupForm # that is what I would like to add (models: boolean field with false default = user activate channel in changing it by true thanks to the forms
def get_context_data(self, **kwargs):
context = super(CheckoutDetail, self).get_context_data(**kwargs)
context['form'] = self.get_form()
return context
def form_valid(self, form):
if form.is_valid():
form.instance.sugargroup = self.object
form.instance.user = self.request.user
form.save()
return super(CheckoutDetail, self).form_valid(form)
else:
return super(CheckoutDetail, self).form_invalid(form)
### I don't know how I can implement this into: def form_valid
def form_valid(self, validation_form):
validation_form.instance.user = self.request.user
validation_form.save()
return super(CheckoutDetail, self).form_valid(validation_form)
######
def post(self,*args,**kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_valid(form)
def get_success_url(self):
return reverse('checkout:checkout_detail',kwargs={"slug":self.object.slug})
...
回答1:
You can do it by adding a name to identify the submit button of the form submitted.
So your markup would look something along the lines of;
<form action="" method="post">
{{ form_1 }}
<input type="submit" name="form_1" value="Submit" />
</form>
<form action="" method="post">
{{ form_2 }}
<input type="submit" name="form_2" value="Submit" />
</form>
Then you can figure out which form was submitted in the post
method;
def post(self, *args, **kwargs):
if 'form_1' in request.POST:
process_form_1()
elif 'form_2' in request.POST:
process_form_2()
来源:https://stackoverflow.com/questions/63944696/django-def-form-valid-with-two-forms