【发布时间】:2021-09-06 06:53:13
【问题描述】:
我尝试在 Django 的应用程序中创建一个表单,但浏览器中没有显示任何内容。
这是我的 app.models.py :
from django.db import models
class Scrape(models.Model):
query = models.CharField(max_length=100)
author = models.CharField(max_length=100)
date = models.DateTimeField('date scraped')
h3 = models.TextField(max_length=500)
links = models.TextField(max_length=10000)
meta = models.TextField(max_length=10000)
这里是我的 app.forms.py :
from django.forms import ModelForm
from app.models import Scrape
class ScrapeForm(ModelForm):
class Meta:
model = Scrape
fields = ['query',]
这里是我的 app.views.py :
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.template import loader
from django.http import HttpResponse
from django import forms, template
from .forms import ScrapeForm
@login_required(login_url="/login/")
def index(request):
context = {}
context['segment'] = 'index'
html_template = loader.get_template( 'index.html' )
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/login/")
def pages(request):
context = {}
# All resource paths end in .html.
# Pick out the html file name from the url. And load that template.
try:
load_template = request.path.split('/')[-1]
context['segment'] = load_template
html_template = loader.get_template( load_template )
return HttpResponse(html_template.render(context, request))
except template.TemplateDoesNotExist:
html_template = loader.get_template( 'page-404.html' )
return HttpResponse(html_template.render(context, request))
except:
html_template = loader.get_template( 'page-500.html' )
return HttpResponse(html_template.render(context, request))
def get_query(request):
if request.method == 'POST':
form = ScrapeForm(request.POST)
if form.is_valid():
print('coucou')
return redirect('/scraping')
else:
form = ScrapeForm()
return render(request, "scraping.html", {'form': form})
这里是我的 scraping.html:
<form class="navbar-search form-inline mr-3 d-none d-md-flex ml-lg-auto post-form" action="" method="POST">{% csrf_token %}
<div class="form-group mb-0">
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-search"></i></span>
</div>
{{ form }}
<input class="input-group-text" type="submit" value="OK" style="color:initial">
</div>
</div>
</form>
当我检查 html 页面时,表单不存在。
我尝试了 {{form.as_p}} 但没有任何反应。
当我尝试使用 manage.py shell 时,我得到了结果
你能帮帮我吗?
【问题讨论】:
-
您必须使用
{{ form.as_p }}查看此帖子以获取更多信息docs.djangoproject.com/en/3.2/topics/forms/… -
我已经尝试使用 .as_p 但没有任何反应。
-
你也必须在
forms.py中添加查询字段。 -
是的。我做到了。 class ScrapForm(ModelForm): class Meta: model = Scrap fields = ['query',] Bt 它对我不起作用。
-
你在 shell 中尝试了什么?
标签: django forms django-views django-forms django-templates