将数据从FormView传递到DetailView

时间:2018-11-01 01:01:55

标签: django django-views

我正在尝试将Celery包括在我的项目中,以便它异步创建Hashtag对象。但是,我需要检查Hashtag对象是否已经由Celery创建。为此,我在get()中用以下方法覆盖了SearchResultsView

if Hashtag.objects.filter(search_text=self.search_text).exists():

具体来说,我不确定为什么search_text=self.search_text不起作用?也许,需要我重写get_context_data中的FormView才能将search_filter数据传递到DetailView吗?或者,我应该在使用self.get_object()语句之前在get()中使用if吗?

Models.py

class Hashtag(models.Model):
    search_text = models.CharField(max_length=140, primary_key=True)

Views.py

class HashtagSearch(FormView):
    model = Hashtag
    form_class = SearchHashtagForm

    def get_success_url(self, search_filter, **kwargs):
        return reverse('mapping_twitter:results', kwargs={'pk':search_filter})

    def form_valid(self, form):
        search_filter = self.get_tweets(form)
        iterate_tweets.delay(search_filter)
        return HttpResponseRedirect(self.get_success_url(search_filter))

    def get_tweets(self, form):
        search_filter = self.request.POST.get('search_text').lower().lstrip("#")
        return search_filter


class SearchResultsView(DetailView):
    model = Hashtag
    template_name = 'mapping_twitter/results.html'

    def get(self, request, *args, **kwargs):
        if Hashtag.objects.filter(search_text=self.search_text).exists():
             self.draw_histogram(request)
        return super(SearchResultsView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(SearchResultsView, self).get_context_data(**kwargs)
        return context

1 个答案:

答案 0 :(得分:1)

我推测问题与您的“超级”有关。您的“获取”将返回从DetailView.get()继承的SearchResultsView.get(),但随后不会使用您的特定添加内容修改对象。也许:

def get(self, request, *args, **kwargs):
    s = super(SearchResultsView, self).get(request, *args, **kwargs)  
      #s is a [httpResponse][1] object
    if Hashtag.objects.filter(search_text=self.search_text).exists():
         s['hist'] = self.draw_histogram(request)
    return s

https://docs.djangoproject.com/en/2.1/ref/request-response/#setting-header-fields