Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Catch argument in Class based FormView

On my page, i need to display the post detail and a comment form for viewer to post comment. I created 2 generic views:

# views.py
class PostDetailView (DetailView):
  model = Post
  context_object_name = 'post'
  template_name = 'post.html'

  def get_context_data(self, **kwargs):
    context = super(PostDetailView, self).get_context_data(**kwargs)
    context['comment_form'] = CommentForm()
    return context

class AddCommentView(FormView):
  template_name = 'post.html'
  form_class = CommentForm
  success_url = '/'

  def form_valid(self, form):
    form.save()
    return super(AddCommentView, self).form_valid(form)

  def form_invalid(self, form):
    return self.render_to_response(self.get_context_data(form=form))

detail = PostDetailView.as_view()
add_comment = AddCommentView.as_view()


# urls.py 
....
url(r'^(?P<pk>\d+)/$', view='detail'),
url(r'^(?P<post_id>\d+)/add_comment/$', view='add_comment'),

....

Error would occur in the AddCommentView,since I haven't specified the post's id for the comment. How can I access the post_id in the AddCommentView?

like image 254
Thai Tran Avatar asked May 01 '12 15:05

Thai Tran


People also ask

How do you call class based views in Django?

import asyncio from django. http import HttpResponse from django. views import View class AsyncView(View): async def get(self, request, *args, **kwargs): # Perform io-blocking view logic using await, sleep for example. await asyncio.

How do you use decorators in class based view in Django?

You need to apply the decorator to the dispatch method of the class based view. This can be done as follows: class ProfileView(View): @youdecorator def dispatch(self,request,*args,**kwargs): return super(ProfileView,self). dispatch(request,*args,**kwargs) //Rest of your code.

What is Form_valid in Django?

Model form views provide a form_valid() implementation that saves the model automatically. You can override this if you have any special requirements; see below for examples. You don't even need to provide a success_url for CreateView or UpdateView - they will use get_absolute_url() on the model object if available.

What is CBV in Django?

Django has two types of views; function-based views (FBVs), and class-based views (CBVs). Django originally started out with only FBVs, but then added CBVs as a way to templatize functionality so that you didn't have to write boilerplate (i.e. the same code) code over and over again.


1 Answers

self.kwargs['post_id'] or self.args[0] contains that value

Docs

like image 57
San4ez Avatar answered Oct 15 '22 15:10

San4ez