在ManyToManyField中设置带有id的默认隐藏值

时间:2014-02-25 13:57:18

标签: django django-models django-forms many-to-many django-views

我在models.py中有这两个人:

class Tag(models.Model):
    name = models.CharField(max_length=100)
    movies = models.ManyToManyField(Movie)

class Movie(models.Model):
    title = models.CharField(max_length=120)
    release_year = models.IntegerField('release year', default=0000)
    plot = models.CharField(max_length=400)
    pub_date = models.DateTimeField('date published')

,这在views.py

class TagCreate(LoginRequiredMixin, CreateView):
    model = Tag
    success_url = '/movies/ratings/'
    fields = ["name"]

我尝试使用当前电影的值设置Tag类中的“movies”字段我是“taggin” 网址是:

url(r'^(?P<movie_id>\d+)/tag/$', TagCreate.as_view(), name='tag'),

先进的Thanxs!

1 个答案:

答案 0 :(得分:2)

不要将其作为表单上的隐藏字段。数据在URL中,您可以从那里获取。这样做的地方是form_valid

def form_valid(self):
    result = super(TagCreate, self).form_valid()
    movie = Movie.objects.get(pk=self.kwargs['movie_id'])
    self.object.movies.add(movie)
    return result