首页 > 解决方案 > 如何修复在 html 中不显示表单小部件

问题描述

我是 django 的新手。我需要创建表单小部件作为输入,以将数据从输入推送到脚本。问题是我的表单没有显示,我不知道错误在哪里。我的目标是从输入中获取数据,以便在数据库 api 中找到并保存在我的数据库中。感谢您的建议。

视图.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)

表格.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' })}

模型.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>

标签: django

解决方案


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

视图.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>

推荐阅读