我有一个拥有公司列表的Django应用程序,当用户点击一家公司时,他们会看到该公司的所有详细信息。现在我正在尝试添加标签功能,以便任何使用可以将标签添加到公司,他们也可以搜索。我创建了表单和模板的东西,但是现在我被困在如何将它连接到View中,特别是使用新标签更新公司模型。Django如何将taggit标签添加到模板中的模型
Forms.py
class TagForm(forms.Form):
tag = forms.CharField(label='Tag', max_length=100)
class Meta:
model = Company
field = 'tag'
模板
<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
UPDATE
我得到的错误“'TagForm'对象没有'save'属性。当我将forms从form.Form更改为forms.FormModel时,出现以下错误:“禁止创建没有'fields'属性或'exclude'属性的ModelForm; TagForm需要更新。”我没有试图创建一个模型,而是通过表单更新它。
Taggit在模型
class Company(models.Model):
company_name = models.CharField(max_length=200)
tags = TaggableManager()
当你尝试这个时会发生什么?请注意,您在标题中提到了taggit,但代码中没有提及它。 –