models.py:
models.py:
class Tag(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) class Post(models.Model): user = models.ForeignKey(User) tag = models.ManyToManyField(Tag) title = models.CharField(max_length=100) content = models.TextField() created = models.DateTimeField(default=datetime.datetime.now) modified = models.DateTimeField(default=datetime.datetime.now) def __unicode__(self): return '%s,%s' % (self.title,self.content) class PostModelForm(forms.ModelForm): class Meta: model = Post class PostModelFormNormalUser(forms.ModelForm): class Meta: model = Post widgets = { 'tag' : TextInput() } exclude = ('user', 'created', 'modified') def __init__(self, *args, **kwargs): super(PostModelFormNormalUser, self).__init__(*args, **kwargs) self.fields['tag'].help_text = None我在views.py中尝试了(看起来不正确的方式)
what i tried in views.py: (that doesn't look the correct way)
if request.method == 'POST': form = PostModelFormNormalUser(request.POST) print form print form.errors tagstring = form.data['tag'] splitedtag = tagstring.split() if form.is_valid(): temp = form.save(commit=False) temp.user_id = user.id temp.save() post = Post.objects.get(id=temp.id) l = len(splitedtag) for i in range(l): obj = Tag(name=splitedtag[i]) obj.save() post.tag.add(obj) post = Post.objects.get(id=temp.id) return HttpResponseRedirect('/viewpost/' + str(post.id)) else: form = PostModelFormNormalUser() context = {'form':form} return render_to_response('addpost.html', context, context_instance=RequestContext(request))任何人都可以发布示例完成代码编辑,以保存到Post表,标签表和post_tag表?
Can anyone post example complete code editing this to save into Post table, Tag table and post_tag table?
输入表单将包含一个文本框以键入'title'和texarea for 'content'和一个文本框,键入'tag'作为字符串。标签字符串由空格分隔。我需要将这些标记词保存到Tag表中,并在post_tag表中映射。
The input form will contain a textbox to type 'title' and texarea for 'content' and a textbox to type 'tag' as string. The tag string is seperated by space. I need to save those tag words into Tag table and map in post_tag table.
我该怎么做?
推荐答案如果你想标注标签,你可以使用django-tagging或django-taggit
As an aside, if you're implimenting tagging, you could just use django-tagging or django-taggit
code.google/p/django-tagging/
django-taggit.readthedocs/en/latest/index.html
djangopackages/grids / g / tagging /
更多推荐
怎么可以在django中保存manytomany字段?
发布评论