Django& Javascript:从模板添加ManyToManyField的条目

时间:2015-06-18 04:20:40

标签: javascript python django

我是django的初学者,我现在面临如何在ManyToManyField中添加条目的问题。 这是我在models.py中的代码:

class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)

# The additional attributes we wish to include for a user.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)

# Tree field is used to store user's favourite trees
tree = models.ManyToManyField(Tree, blank=True)


def __unicode__(self):
    return self.user.username

我想要做的是在我的模板中有一个按钮(例如tree.html),如果我单击此按钮,该条目将被添加到用户个人资料的树字段中的ManyToManyField中。

任何建议都将受到赞赏!!

非常感谢。

1 个答案:

答案 0 :(得分:0)

urls.py

urlpatterns = [
    ...
    url(r'^like_tree/(\d+)/$', views.like_tree, name='like_tree'),
    ...
]

views.py

from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

@require_POST
@login_required
def like_tree(request, tree_id):
    tree = get_object_or_404(Tree, pk=tree_id)
    request.user.userprofile.tree.add(tree)
    return redirect(<specify redirect url here>)

模板(将'like_tree'更改为实际网址名称,例如'myapp:like_tree'

<form method="post" action="{% url 'like_tree' tree.id %}">
    <button type="submit">Like</button>
</form>

实际上,渲染模板有很多选项。 This also may be usefull (about Ajax and CSRF)