我是Django的新手。我使用下面的链接在第一个用例中首次在Django中实现了表单集,但我陷入了这个错误。
即使我使用的是formset,HTML也会查找名为“ form”的变量。我不确定是什么问题。
https://medium.com/@taranjeet/adding-forms-dynamically-to-a-django-formset-375f1090c2b0
urls.py:
from django.urls import path
from django.urls import re_path
from . import views
from .views import (
create_projectform_normal,
)
urlpatterns=[
path('', views.index, name='index'),
path('dashboard', views.dashboard, name='dashboard'),
path('madhan', create_projectform_normal, name='create_projectform_normal'),
HTML:
<form class="form-horizontal" method="POST" action="">
{% csrf_token %}
{{ formset.management_form }}
0999999999
{% for form in formset %}
<div class="row form-row spacer">
<div class="col-2">
<label>{{form.project_title.label}}</label>
</div>
<div class="col-4">
<div class="input-group">
{{form.project_title}}
<div class="input-group-append">
<button class="btn btn-success add-form-row">+</button>
</div>
</div>
</div>
</div>
{% endfor %}
<div class="row spacer">
<div class="col-4 offset-2">
<button type="submit" class="btn btn-block btn-primary">Create</button>
</div>
</div>
</form>
SaveForms.py:
Views.py:
from django.shortcuts import render, redirect
from projects.forms import ProjectForm2Formset
from projects.models import ProjectModel
def create_projectform_normal(request):
template_name = 'pages/form.html'
heading_message = 'Formset Demo'
if request.method == 'GET':
formset = ProjectForm2Formset(request.GET or None)
elif request.method == 'POST':
formset = ProjectForm2Formset(request.POST)
if formset.is_valid():
for form in formset:
# extract name from each form and save
project_title = form.cleaned_data.get('project_title')
# save book instance
if project_title:
ProjectForm2(project_title=project_title).save()
# once all books are saved, redirect to book list view
return redirect('form')
return render(request, template_name, {
'formset': formset,
'heading': heading_message,
})
Models.py
class ProjectModel(models.Model):
project_title = models.CharField(max_length=255)
class Meta:
db_table = 'Project'
def __str__(self):
return self.project_title
Forms.py:
class ProjectForm2(forms.Form):
project_title = forms.CharField(
label='Project Title',
widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the project Title'
})
)
ProjectForm2Formset = formset_factory(ProjectForm2, extra=1)