0

我正在学习 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 %}
4

1 回答 1

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)
于 2018-08-20T21:18:18.627 回答