我有一个Django应用程序,其中包含公司列表,当用户点击公司时,他们会看到该公司的所有详细信息。现在我正在尝试添加标签功能,以便任何使用都可以向公司添加标签,他们也可以搜索标签。我已经创建了表单和模板的东西,但现在我已经陷入了如何将其连接到View中,特别是使用新标签更新Company模型。
Forms.py
<div class="add-tag-form">
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default btn-sm">Add</button>
</form>
</div>
模板
class CompanyDetails(generic.DetailView):
model = Company
template_name = 'company_details.html'
# This was my attempt to work it into the View...
def post(self, request, *args, **kwargs):
form = TagForm(request.POST)
if form.is_valid():
tag = form.save(commit=False)
tag.company = Company.objects.get(pk=pk)
tag.save()
def get_context_data(self, **kwargs):
pk = self.kwargs.get('pk')
context = super(CompanyDetails, self).get_context_data(**kwargs)
context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date')
context['transcripts'] = Transcripts.objects.filter(company_id=pk).order_by('-date')
context['form'] = TagForm()
# Yahoo Finance API data
stock_symbol = self.object.stock_symbol
data = Share(stock_symbol)
stock_open = data.get_open()
year_range = data.get_year_range()
fifty_day_moving_average = data.get_50day_moving_avg()
market_cap = data.get_market_cap()
yahoo_finance = dict()
yahoo_finance['stock_open'] = stock_open
yahoo_finance['year_range'] = year_range
yahoo_finance['fifty_day_moving_average'] = fifty_day_moving_average
yahoo_finance['market_cap'] = market_cap
context['yahoo_finance'] = yahoo_finance
# Yahoo News RSS data
yahoo_news = feedparser.parse("http://finance.yahoo.com/rss/headline?s=" + stock_symbol)
yahoo_news = yahoo_news['entries']
for item in yahoo_news:
item['published'] = datetime.strptime(item['published'], '%a, %d %b %Y %H:%M:%S %z')
context['yahoo_news'] = yahoo_news
return context
查看
class Company(models.Model):
company_name = models.CharField(max_length=200)
tags = TaggableManager()
更新
我得到的错误“'TagForm'对象没有属性'save'”。当我将窗体从forms.Form更改为forms.FormModel时,我收到以下错误“禁止创建没有'fields'属性或'exclude'属性的ModelForm;表单TagForm需要更新。”我不是要创建一个模型,而是通过表单更新它。
Taggit用于模型
<paper-drawer-panel id="paperDrawerPanel" force-narrow disable-swipe disable-edge-swipe ></paper-drawer-panel>
答案 0 :(得分:1)
您可以做的一件事就是为标签创建一个简单的表单,就像您所做的那样,但删除Meta信息并更新post方法只是在公司中添加标签。如下所示:
# forms.py
class TagForm(forms.Form):
tag = forms.CharField(label='Tag', max_length=100)
# views.py
class CompanyDetails(generic.DetailView):
...
# This was my attempt to work it into the View...
def post(self, request, *args, **kwargs):
company = self.get_object()
form = TagForm(request.POST)
if form.is_valid():
company.tags.add(form.cleaned_data['tag'])
return self.render_to_response(self.get_context_data())