0
votes

views.py

def fadded(request):
    if request.method == "POST":
        fform = FtForm(request.POST)
        bform = BgForm(request.POST)
        if fform.is_valid() and bform.is_valid():
            bcontent=bform.save()
            fcontent=fform.save()

        else:
            return render_to_response("ft.html", {
            "fform": fform,
            "bform": bform,
            },context_instance=RequestContext(request))
    return HttpResponse('OK!')

ft.html

...
    {% if form.errors%}
    
    {% for error in form.errors %} {{ error|escape }} {% endfor %}
{% endif %} ...

There are two modelforms: fform and bform. They represent two different models, but are used in same template. I'm trying to save both and to get form-/fielderrors from both. But if there are already fform.errors, django doesn't shows bform.errors(and propably doesn't even create bform). Any proposals for a different way?

2

2 Answers

0
votes

django doesn't shows bform.errors(and propably doesn't even create bform)

Given your setup, both forms are passed data and are ready to be validated. There shouldn't be a problem.

In your template, you'd have to display both forms errors (I only see one form being checked in your template)

{{ fform.errors }} <!-- show errors from fform -->
{{ bform.errors }} <!-- show errors from bform -->
0
votes

You need to use Class based views!

Here is a quick example of using multiple forms in one Django view.

from django.contrib import messages from django.views.generic import TemplateView

from .forms import AddPostForm, AddCommentForm from .models import Comment

class AddCommentView(TemplateView):

    post_form_class = AddPostForm
    comment_form_class = AddCommentForm
    template_name = 'blog/post.html'

    def post(self, request):
        post_data = request.POST or None
        post_form = self.post_form_class(post_data, prefix='post')
        comment_form = self.comment_form_class(post_data, prefix='comment')

        context = self.get_context_data(post_form=post_form,
                                        comment_form=comment_form)

        if post_form.is_valid():
            self.form_save(post_form)
        if comment_form.is_valid():
            self.form_save(comment_form)

        return self.render_to_response(context)     

    def form_save(self, form):
        obj = form.save()
        messages.success(self.request, "{} saved successfully".format(obj))
        return obj

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)

In this example I have found online (on RIP tutorial), we use TEMPLATE VIEW. Class-based views are your way around this. Here is a link to the most up-to-date documentation on how to use class-based views on Django. Have fun reading, and most of all, patience. https://docs.djangoproject.com/en/2.2/topics/class-based-views/

Hopefully, this could help to guide you in the right direction. Looking forward to hearing from how it goes.