如何修复不在html中显示表单小部件的问题

时间:2019-05-24 19:49:15

标签: django

我是django的新朋友。我需要创建表单窗口小部件作为输入,以将数据从输入推送到脚本。问题是我的表格没有显示,我也不知道错误在哪里。我的目标是从输入中获取数据,以便可以在数据库api中找到它并将其保存在我的数据库中。赞赏建议。

views.py

 def data(request):
        url = 'http://www.omdbapi.com/?t={}&apikey=My key is here'

        if request.method == 'POST':
            form = MovieForm(request.POST)
            form.save()

        form = MovieForm()
        movies = Movie.objects.all() #// fetch all objects
        movies_data = []  #//// array for movies and their details
        for movie in movies:
            r = requests.get(url.format(movie)).json() #// gets details from api

            movies_main = {
                'title': movie.title,
                'director': r['Director'],
                'rate': r['imdbRating'],
            }
            movies_data.append(movies_main)
        context = {'movies_data':movies_data}
        return render(request, 'movies/movies.html', context)

forms.py

from django.forms import ModelForm, TextInput
    from .models import Movie

    class MovieForm(ModelForm):
        class Meta:
            model = Movie
            fields = ['title']
            widgets = {'title' : TextInput(attrs={'class' : 'id', 'placeholder' : 'put your id' })}

models.py

from django.db import models

# Create your models here.
class Movie(models.Model):
    title = models.CharField(max_length=50)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'movies'

模板

    {% load static %}
        <html>
        <head>
        <link rel="stylesheet" href="{%static 'movies/style.css' %}">
        <script type="text/javascript">

        </script>
        </head>

        <body>
            <div class='container'>
                <header>Movies API</header>
                    <form method="POST" action='/index'>  
                        {% csrf_token %}
                        {{ form.title }}
                        <input type='submit' class='sub', value='add'> 
                    </form>
            </div>
        </body>
        </html>

1 个答案:

答案 0 :(得分:0)

Form未显示在模板中,因为它没有在模板上下文中传递以进行渲染。让我们这样尝试吧。

views.py

from django.http import HttpResponseRedirect
def data(request):
    url = 'http://www.omdbapi.com/?t={}&apikey=My key is here'
    if request.method == 'POST':
        form = MovieForm(data=request.POST)
        form.save()
        return HttpResponseRedirect(request.get_full_path()) # During HTTP POST processing, refresh page (Or change with your logic in future).
    else:
        form = MovieForm()
        movies = Movie.objects.all() #// fetch all objects
        movies_data = []  #//// array for movies and their details
        for movie in movies:
            r = requests.get(url.format(movie)).json() #// gets details from api
            movies_main = {
                'title': movie.title,
                'director': r['Director'],
                'rate': r['imdbRating'],
            }
            movies_data.append(movies_main)
    context = {
        'form': form,
        'movies_data': movies_data,
    }
    return render(request, 'movies/movies.html', context)

您的模板

{% load static %}
        <html>
        <head>
        <link rel="stylesheet" href="{%static 'movies/style.css' %}">
        <script type="text/javascript">

        </script>
        </head>

        <body>
            <div class='container'>
                <header>Movies API</header>
                    <form method="POST" action='/index'>  
                        {% csrf_token %}
                        <!-- you also can use {#% form.as_p %#} or {#% form.as_table %#}, but form.title is fine also. -->
                        {{ form.title }}
                        <input type='submit' class='sub', value='add' /> 
                    </form>
            </div>
        </body>
        </html>