简体   繁体   中英

Django - Pass context dictionary between views?

I have a detail view for each page and a CommentView for typing comments directly on to those pages. In the comment view, an instance of the Comment model is created which stores: the content of the comment, the author and the page id for the page it was written on. The 'context' dictionary stores the page it was written on, but this is not defined in the CommentView.

My question: How do I pass the context dictionary from the detail view to the CommentView so I can access the page id? Or is there a better way to do this?

class CityDetailView(DetailView):
    model = City
    template_name = 'blog/city.html'
    context_object_name = 'cities'

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


class CommentView(View):

    #template_name = 'comment.html'    

    def post(self, request):
        form = CommentForm(request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']
            print(form.cleaned_data)

            ######################## This is where I need to use context ########################

            new_comment = Comment(content=content,
                                  author=request.user, 
                                  page_id=City.objects.filter(title=context['cities']).first().id)

            ######################################################################################

            new_comment.save()
            return HttpResponseRedirect('/about')
        else:
            return HttpResponseRedirect('/about')

The url for CommentView could include a parameter indicating an identifier for the city that you could use to set page_id for the comment form. Or you could create a hidden input on the form doing the same thing if you don't want to include it in the url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM