wtfzn
wtfzn

Reputation: 538

How to access multiple generic views from one template?

first, sorry for my noobish question, but I didn't find an answer for my question.

I'm trying figure out, how to access multiple generic views from one template in Django.

Example: I have a Blogpost Detail-View:

class PostView(generic.DetailView):
    model = Post
    template_name = "blog/detail.html"

And a form to create a new comment:

class CommentCreate(CreateView):
model = Comment
    template_name = "blog/test.html"
    fields = ['author', 'email', 'comment']

In my urls.py, I'm accessing the Detail-View with this statement:

url(r'^(?P<pk>\d+)/$', views.PostView.as_view(), name='detail')

Obviously I'm not able to access my form by calling the as_view()-function on a DetailView.

With this given, i really can't figure out, how to add the CommentCreate-Form to my template.

How can I access the data of a generic view or form inside the template of another generic view?

Thanks for your help!

Upvotes: 0

Views: 750

Answers (2)

wtfzn
wtfzn

Reputation: 538

After the advice from @bruno desthuilliers, I tried a different approach without the use of generic views:

Added in models.py:

from django.forms import ModelForm

class CommentCreate_ungen(ModelForm):
class Meta:
    model = Comment
    fields = ['author', 'email', 'comment']

Used in views.py instead of generic class based views these functions:

from django.shortcuts import render_to_response
from blog.models import CommentCreate_ungen

def index_ungen(request):
    post = Post.objects.all()
    return render_to_response('blog/index_ungen.html', {'post': post})

def detail_ungen(request, pk):
    post = Post.objects.get(pk=pk)
    form = CommentCreate_ungen()
    return render_to_response('blog/detail_ungen.html', {'post': post, 'form': form})

For me, this seems much easier!

Upvotes: 0

Leandro
Leandro

Reputation: 2247

Using mixins! Maybe you could use SingleObjectMixin, but I'll show you how to use (and create) a mixin.

class DetailViewMixin(object):
    details_model = None
    context_detail_object_name = None

    def get_context_data(self, **kwargs):
        context = super(DetailViewMixin, self).get_context_data(**kwargs)
        context[self.context_detail_object_name] = self.get_detail_object()
        return context

    def get_detail_object(self):
        return self.details_model._default_manager.get(pk=self.kwargs['pk'])

class CommentCreate(DetailViewMixin, CreateView):
    details_model = Post
    context_detail_object_name = 'post'
    model = Comment
    template_name = "blog/test.html"
    fields = ['author', 'email', 'comment']

Now, you have a'form' variable in your template and a 'post' variable.

EDIT

You can't use 2 generic views together, both use the SingleObjectMixin for their model.

Hope helps

Upvotes: 2

Related Questions