怎么可以在django中保存manytomany字段?

编程入门 行业动态 更新时间:2024-10-23 09:32:45
本文介绍了怎么可以在django中保存manytomany字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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字段?

本文发布于:2023-10-23 02:05:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   django   manytomany

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!