开发者

Django, form in menu and form in view conflicting

I want to put a form in my menu to be able to choose a project, keep this information and be able to change it at all time in the site. I'm using a context_processor to implement it and (trying to) use session variable to keep the information.

However I bumped into a problem. The form is included in the base template which is included in all other templates. Some these other templates also contain a form and apparently there is a sort of conflict between the menu form and the other ones. For example, when I try to validate a view form, it tells me that the menu form fields are not filled in, and it shouldn't ca开发者_JAVA技巧re about it.

I tried to put a different action url with no effect.

Is what I'm trying to do even possible ? If so, how can I avoid the conflicts ?

The form for the menu is called in a context_processor, the code of the function calling it :

def display_select_proj(request):
        if request.method == "POST":
                form = SelectForm(request.POST)
                if form.is_valid():
                        proj = form.save()

                        request.session['proj'] = proj

        else:
                form = SelectForm()
                proj = ""

        return {'select_form': form}

I added the display_select_proj to the TEMPLATE_CONTEXT_PROCESSORS and finally in the base template i display it with {{ select_form }}


Since you have two forms, you need to have something to tell you which form actually got submitted. This will tell your display_select_proj function whether to try to validate the form.

Usually, with a plain old form, you have a Submit button, and if you have two of them, the value for each submit button is different so you can check it to tell which form got submitted. Failing that, you need to add a hidden field to tell you which form got submitted.

Once you can determine which form got submitted, you can then use that to figure out if you need to bind a form or leave it unbound. For example, in your code, if your project selector has a Submit button named "action" with value "Change Project":

def display_select_proj(request):
    if request.method == "POST" and (request.POST.get("action", "") 
        == "Change Project"):
        form = SelectForm(request.POST)
        if form.is_valid():
            proj = form.save()
            request.session['proj'] = proj
    else:
        form = SelectForm()
        proj = ""

    return {'select_form': form}

Note that every form will need the extra check to see if that particular form has been submitted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜