开发者

django form in multiple views

I want my form to display in multiple views开发者_运维知识库 with this behaviour:

1.) Form errors are shown in the view that the user submitted the form from.

2.) If form validates, send user back to the view they submitted the form from.

How might I be able to do that?


I'm pretty sure the first behavior is default, if i understand your question correctly. For the second one, if you don't redirect after saving and validation, it should just re-render the view that you submitted from. Placing a success variable is probably good to see if the form saved. Here is an example of using a single form in multiple views.

models.py:

class MyModel(models.Model):
    name = models.CharField()

forms.py:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

views.py:

def first_view(request):
    success = False
    if request.method=="POST":
        form = MyModelForm(request.POST)
        if form.is_valid():
            form.save()
            success = True
    else:
        form = MyModelForm()

    context = { 'form':form,
                'success': success, }

    return render_to_response('first_view_template.html', context,
            context_instance=RequestContext(request))

def second_view(request):
    success = False
    if request.method=="POST":
        form = MyModelForm(request.POST)
        if form.is_valid():
            form.save()
            success = True
    else:
        form = MyModelForm()

    context = { 'form':form,
                'success': success, }

    return render_to_response('second_view_template.html', context,
            context_instance=RequestContext(request))


Have you tried the Django Form preview, if I am not wrong it can be used for your purpose

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜