我正在尝试将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
答案 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