在同一视图中搜索和显示

时间:2018-08-20 21:07:58

标签: python django imdbpy

我正在学习Django,我想知道是否有更好的方法可以做到这一点。基本上,我试图从IMDbPy API获取电影并显示电影信息。到目前为止,我正在使用一个视图来获取信息并显示它(使用两个不同的模板)。这是正确的方法吗?还是应该将其分为两个不同的视图?如果是这样,我该怎么办?

观看次数

def get_movie_name_view(request):
form = GetMovieName(request.POST or None)
if form.is_valid():
    ia = IMDb()
    movies = ia.get_movie(form.cleaned_data['movie_title'])
    context = {'title': movies['title'],
               'directors': movies['directors'],
               'runtime': movies['runtime'],
               'year': movies['year'],
               'genre': movies['genres'],
               'form': form
               }
    return render(request, 'show_movie_info.html',context)
context = {
    'form': form
}
return render(request, 'get_movie_name.html', context)

型号

class Movie(models.Model):
  title = models.CharField(max_length=250)
  directors = models.CharField(max_length=300)
  runtime = models.IntegerField()
  year = models.DateField()
  genre = models.CharField(max_length=100)

表格

class GetMovieName(forms.Form):
movie_title = forms.CharField(label='Movie Title', max_length=100)

获取电影模板

{%  extends 'base.html' %}

{% block content %}
    <form method="POST"> {% csrf_token %}
        {{form.as_p}}
    <input type="submit", value="Submit" />
    </form>
{%  endblock %}

显示电影模板

{%  extends 'base.html' %}

{% block content %}
    <p> Title: {{ title }} </p>
    <p> Duration: {{ runtime }} minutes </p>
    <p> Director: {{ directors }} </p>
    <p> Year: {{ year }} </p>
    <p> Genre: {{ genre }}</p>


{%  endblock %}

1 个答案:

答案 0 :(得分:0)

我做了一些更改。

def get_movie_name_view(request):
    form = GetMovieName(request.POST or None)
    # ensure the request is a post
    if request.method == 'POST':
        if form.is_valid():
            ia = IMDb()
            movies = ia.get_movie(form.cleaned_data['movie_title'])
            context = {'title': movies['title'],
                       'directors': movies['directors'],
                       'runtime': movies['runtime'],
                       'year': movies['year'],
                       'genre': movies['genres'],
                       'form': form
                       }
            return render(request, 'show_movie_info.html',context)
    # ensure request is a GET
    if request.method == 'GET':
        context = { 'form': form }
        return render(request, 'get_movie_name.html', context)