Django def form_valid with two forms

强颜欢笑 提交于 2021-01-29 18:24:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!