Django表单未显示

时间:2017-02-04 13:42:03

标签: python django

我现在一直处理个人项目,并且无法解决我在某个特定表单上遇到的问题。我在过去写过成功的Django表单,并在之后对其进行了建模,但我仍然无法显示它。

我的模型看起来像:

name = models.CharField(max_length=100)
director = models.CharField(max_length=50)
genre = models.TextField()
rating = models.IntegerField()
mpaa_rating = models.CharField(max_length=5)
# movie_file = models.FileField()
movie_cover = models.CharField(max_length=100)
cast_list = models.TextField()
year = models.TextField()
url = models.CharField(max_length=100, default='http://www.imdb.com/title/')

我的表格如下:

class Meta:
    model = Movie
    fields = ['url', 'name', 'director', 'genre', 'rating', 'mpaa_rating',   'movie_cover', 'cast_list', 'year']

查看:

context = RequestContext(request)
movie_form = MovieForm()
if request.method == 'POST':
    movie_form = MovieForm(data=request.POST)
    if movie_form.is_valid():
        url = urlrequest.urlopen(movie_form.url)
        movie = BeautifulSoup(url, 'html.parser')
        movie_form.set_name(movie.find(itemprop='name'))
        data = get_movie_data(url)
        movie_form.data['name'] = data[0]
        movie_form.data['director'] = data[4]
        movie_form.data['genre'] = data[7]
        movie_form.data['rating'] = data[3]
        movie_form.data['mpaa_rating'] = data[2]
        movie_form.data['year'] = data[1]
        movie_form.data['cast_list'] = data[5]
        movie_form.data['movie_cover'] = data[6]
        movie_form.save()
        print('movie added')

return render_to_response('add_movie.html', {movie_form: 'movie_form'}, context)

最后是模板:

<form id="movie_form"  method="post" action="{% url 'add_movie' %}">
    {% csrf_token %}
    {{ movie_form.as_p }}

    <input type="submit" value="Save" />
</form>

我已经阅读了关于如何解决问题的堆栈溢出的几个帖子,但是他们都没有修复我的。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您没有将表单发送到模板:

return render_to_response('add_movie.html', {movie_form: 'movie_form'}, 

替换为:

return render_to_response('add_movie.html', {'movie_form': movie_form})

更新

顺便说一句,您应该使用render(),因为它使用RequestContext

如果您想在render_to_response的模板上使用它,则必须添加参数context_instance=RequestContext(request),这可能有点烦人。