我正在尝试使用Taggit让用户能够在提交表单时标记他们的帖子。但我可以成功让他们手动输入(他们的标签),我试图改为复选框。有什么想法吗?
forms.py
class TalesForm(ModelForm):
class Meta:
model = Tale
fields = ('title', 'body', 'tags')
m_tags = TagField()
models.py
class Tale(models.Model):
title = models.CharField(max_length = 50)
body = models.TextField(max_length = 10000)
pub_date = models.DateTimeField(default = datetime.now)
poster = models.CharField(max_length = 30)
tags = TaggableManager()
def __unicode__(self):
return self.title
views.py
def add(request):
if request.user.is_authenticated():
if request.method=='POST':
form=TalesForm(request.POST)
if form.is_valid():
m_tags = form.cleaned_data['tags']
newTale=Tale(title=form.cleaned_data['title'], body=form.cleaned_data['body'], poster = request.user)
newTale.save()
for m_tag in m_tags:
newTale.tags.add(m_tag)
#form.save_m2m()
return HttpResponseRedirect('/home/%s'%newTale.id)
else:
return render_to_response('story/add.html', {'form':form}, context_instance=RequestContext(request))
else:
form=TalesForm()
args = {}
args.update(csrf(request))
args['form'] = form
context= {'form': form}
return render_to_response('story/add.html',context, context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/home')
html
<form method="post" action="/home/add/">
{% csrf_token %}
<div class="register_div">
{% if form.title.errors %}<p class="error" >{{ form.title.errors }}</p>{% endif %}
<p><label for="title"{% if form.title.errors %} class="error"{% endif %}>Title:</label></p>
<p>{{ form.title}}</p>
</div>
<div class="register_div">
{% if form.body.errors %}<p class="error" >{{ form.body.errors }}</p>{% endif %}
<p><label for="body"{% if form.body.errors %} class="error"{% endif %}>Body:</label></p>
<p>{{ form.body }}</p>
</div>
<div class="register_div">
<p><label for="tag">Tags:</label></p>
<p>{{ form.tags }}</p>
</div>
<input type="submit" value="Add Story" name="submit" />
</form>
答案 0 :(得分:4)
以这种方式定义表单:
from taggit.models import Tag
class TalesForm(ModelForm):
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all(),
widget=forms.CheckboxSelectMultiple())
class Meta:
model = Tale
fields = ('title', 'body', 'tags')