Django form not submitting - python

Recently, I've been working on a project to make certain tasks that are crucial to a project I am a part of become a lot easier.
The form was working the last time I checked it (a month ago). Since then, I moved it off of my computer and on to a server. The form is no longer submitting.
#forms.py
from django import forms
from .models import OnlineEssay, HardCopy, FaceToFaceConference
class OnlineEssayClientForm(forms.ModelForm):
class Meta:
model = OnlineEssay
fields = [
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"client_email",
"feedback_primary",
"feedback_secondary",
"essay_file",
]
labels = {
'client_first_name': ('First Name'),
'client_last_name': ('Last Name'),
'client_grade': ('Grade Level (As Number)'),
'client_teacher': ('Teacher'),
'client_email': ('Email Address'),
'feedback_primary': ('I need/would like feedback on:'),
'feedback_secondary': ('And,'),
}
class OnlineEssayTutorForm(forms.ModelForm):
class Meta:
model = OnlineEssay
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"client_email",
"feedback_primary",
"feedback_secondary",
"essay_file",
"essay_tutor",
"essay_feedback",
]
class HardCopyTutorForm(forms.ModelForm):
class Meta:
model = HardCopy
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"feedback_primary",
"feedback_secondary",
"essay_tutor",
"essay_feedback",
]
class FaceToFaceConferenceTutorForm(forms.ModelForm):
class Meta:
model = FaceToFaceConference
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"feedback_primary",
"feedback_secondary",
"essay_tutor",
"essay_feedback_notes",
]
<!-- templates/submit.html -->
{% extends 'base.html' %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block head_title %}Welcome{% endblock %}
</head>
<body>
{% block content %}
<h1>Submit Your Essay</h1>
<div class="bs-callout bs-callout-default">
<p>Fill Out The Form Below, then press Submit</p>
</div
<form method="post" enctype="multipart/form-data">{%csrf_token%}
{{form|crispy}}
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
{% endblock %}
</body>
</html>
#views.py
from django.shortcuts import render
from django import http
# Create your views here.
from .forms import OnlineEssayClientForm
def submit(request):
form = OnlineEssayClientForm(request.POST or None, request.FILES or None)
context = {
"form": form,
"page_title" : "Submit Your Essay",
}
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/success/')
return render(request, "submit.html", context)

It was actually a pretty simple issue. I had forgot to close the </div> tag at the end of the callout. The form submits fine now.

Related

Django Form is not updating the user database

I want to update User database using forms.When I trying to update it remains same the database and not update. So to perform this task ?
forms.py
from django import forms
from django.contrib.auth.models import User
class updateform(forms.ModelForm):
class Meta:
model=User
fields="__all__"
views.py
from django.contrib.auth.models import User
from .forms import updateform
#permission_required('is_superuser')#only superuser can update the data base
def upform(request,id):
emp=User.objects.get(id=id)
if request.method=='POST':
frm=updateform(request.POST,instance=emp)
if frm.is_valid():
frm.save()
return redirect('/')
else:
frm=updateform(instance=emp)
return render(request,'examp.html',{'frm':frm})
examp.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static '/examp.css' %}">
<style>
td,th{
border:1px solid;
text-align:center;
padding:10px;
}
</style>
</head>
<body>
{% include 'include/header.html' %}
<form action="/" method="POST">
{% csrf_token %}
{{ frm.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>
How to update the database using this given form.
Why don't you use CBV generic views?
in yourapp/models.py:
from django.db import models
from django.urls import reverse
from django.contrib.auth import get_user_model
# const for get_absolute_url
#that's suffix will be using in your template names look at urls.py,
#if you need u should change it for smth here and in urls!
DETAIL_SUFFIX = '_detail'
class YourModel(models.Model):
name = models.CharField(default='new', max_length=6)
updated_by = models.ForeignKey(get_user_model(), on_delete=models.PROTECT,
related_name='get_upd_by_user')
def __str__(self):
return f'{self.name}'
def get_absolute_url(self):
return reverse(f'{self.__class__.__name__}{DETAIL_SUFFIX}', kwargs={"pk": self.pk})
You need to define the get_absolute_url method. Then reverse will works properly after you update.
in yourapp/views.py:
#views
from django.views.generic.edit import UpdateView
from django.views.generic import DetailView
# AAA
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import PermissionRequiredMixin
class ProjectSubnetDetailView(LoginRequiredMixin, DetailView):
model = YourModel
template_name = 'your_name_detail.html'
class YourNameUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
model = YourModel
template_name = 'your_name_edit.html'
fields = ('somefield', )
permission_required = ('yourapp.view_yourmodel','yourapp.change_yourmodel')
def form_valid(self, form): # Bind name of current user
form.instance.updated_by = self.request.user
return super().form_valid(form)
Instead of decorator #permission_required in CBV you can use PermissionRequiredMixin(I highly recommend reading about it in the official documentation). In short you must define only in this order:
(LoginRequiredMixin, PermissionRequiredMixin, UpdateView)
First - user must be Authenticated
Second - user must have a rights (or roles, that have a need rights)
Third - thats your generic view for do smth (in this example is update)
For second Attention You must specify in the view those rights that are checked before performing the update in strictly lowercase.
You can define rights in admin panel for some user or create a role and define some rights and add your user into that role. For example i create user and define him some rights for view and change table:
So if your model is called 'YourModel', you should specify 'action_yourmodel'
permission_required = ('yourapp.view_yourmodel','yourapp.change_yourmodel')
in yourapp/urls.py.
from django.urls import path
from .views import YourNameUpdateViewUpdateView, YourNameDetailView
urlpatterns = [
path('YourName/<int:pk>/edit/', YourNameUpdateView.as_view(), name='some_name_edit'),
path('YourName/<int:pk>/detail/', YourNameDetailView.as_view(), name='some_name_detail'),
]
in yourapp/templates/ you have to define 2 templates:
#your_name_detail.html
{% extends '_basetemplate.html' %}
{% block content %}
<div>
<p>{{ object.name }}</p>
</div>
<p>
Update |
</p>
{% endblock content %}
# your_name_edit.html
{% extends '_basetemplate.html' %}
{% block content %}
<h5>Updating {{ object.name }}</h5>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-sm btn-info ml-2" type="submit">Update</button>
</form>
{% endblock content %}

Why Django's POST doesn't do anything - not even an error?

I'm doing an assignment for Uni from Python/Django. One of the things I have to do is to create a form where a user can create a new "tournament" on the website. Frontend doesn't matter at all.
I created a model, added some tournaments from the Admin panel and that works fine. But when I try to create a new tournament from the form, and click the sumbit button, I get redirected to my home page (even though nothing specifies in the HTML or views.py that this should happen), I get no error, no data posted and no info back from the command line.
models.py
class Tournament(models.Model):
title = models.CharField(max_length=30)
creator = models.OneToOneField(User, on_delete=models.CASCADE)
players = models.ManyToManyField(User, related_name="players",)
created_date = models.DateField(auto_now=True)
start_date = models.DateField(auto_now=True)
max_players = models.IntegerField(
null=True, validators=[MinValueValidator(2), MaxValueValidator(64)])
slug = models.SlugField(unique=True, db_index=True)
def __str__(self):
return f"{self.title} \n {self.creator} \n {self.max_players}"
Forms.py
class TournamentForm(forms.ModelForm):
class Meta:
model = Tournament
#exclude = ["slug"]
fields = "__all__"
views.py
class TournamentView(View):
def get(self, request):
form = TournamentForm()
print(form.errors)
return render(request, "tournament_app/new_tournament.html", {
"form": form
})
def post(self, request):
form = TournamentForm(request.POST)
if form.is_valid():
print(form.errors)
form.save()
return redirect("/thank-you")
print(form.errors)
return render(request, "tournament_app/new_tournament.html", {
"form": form
})
new_tournament.html
{% extends "base.html" %}
{% block title %} Create New tournament {% endblock title %}
{% extends "base.html" %}
{% block title %}
Create New tournament
{% endblock title %}
{% block content %}
<form action="/" method="POST">
{% csrf_token %}
{% for field in form%}
<div class="form-control">
{{field.label_tag}}
{{field}}
</div>
{% endfor %}
<button type="submit">Send</button>
</form>
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock title %}</title>
</head>
<body>
{% if user.is_authenticated %}
<p style="text-align:right;">You are logged in as <b>{{user.username}}</b></p>
{% else %}
<p style="text-align:right;"><b>Anonymous user</b></p>
{% endif %}
<button type = "button"> Main Page </button>
<button type = "button"> Login </button>
{% block content %}{% endblock content %}
</body>
</html>
As you can see in the views.py I tried to check for at least any errors as suggested on some other post years ago, but I get NO response back.
In the command line i see it as such:
[22/Jul/2021 13:33:10] "GET /new-tournament HTTP/1.1" 200 1839
[22/Jul/2021 13:33:19] "POST / HTTP/1.1" 200 744
I have absolutely no experience in WebDev and no experience in Django. Can you please help me identify problem? If there was at least some error response or anything like that.
I get redirected to my home page (even though nothing specifies in the HTML or views.py that this should happen)
Oh, but you're specifying that, quite explicitly. :-)
You're POSTing to /, not /new-tournament (your TournamentView).
<form action="/" method="POST">
Get rid of the action to post to the current URL instead.
<form method="POST">
Additionally, you can simplify your TournamentView to a CreateView:
class TournamentView(CreateView):
model = Tournament
template_name = "tournament_app/new_tournament.html"
success_url = "/thank-you"
(yes, that should be all)

How can I make Django render in the browser?

I'm trying to utilize Django forms.ModelForm function. However, I can not get it to render in the browser (Firefox and Chrome tested). In both browser inspection of code, the table\form does not show and there is no error coming from Django at all. The only thing that shows from the html file is the "Save button" Is there something I am missing here?
In Models.py
from django.db import models
class Product_sell_create(models.Model):
product_product_sell = models.CharField(max_length=120)
product_price_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_volume_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_location_sell = models.CharField(max_length=120)
product_description_sell = models.TextField(blank=False, null=False)
Forms.py
from django import forms
from .models import Product_sell_create
class ProductName(forms.ModelForm):
class Meta:
model = Product_sell_create
fields = [
'product_product_sell',
'product_volume_sell',
'product_price_sell',
'product_location_sell',
'product_description_sell'
]
Views.py
from django.shortcuts import render
from .forms import ProductName
def products_create_view(request):
form = ProductName(request.POST or None)
if form.is_valid():
form.save()
form = ProductName()
context = {
'form': form
}
return render(request, "sell.html", context)
sell.html
{% include 'navbar.html' %}
<h1> Upper test</h1>
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST </h1>
{% block content %}
{% endblock %}
just did it, you would have problems POSTing your object too:
views.py:
from django.shortcuts import render, redirect
from .forms import ProductName
from .models import Product_sell_create
def products_create_view(request):
if request.method == 'POST':
form = ProductName(request.POST)
if form.is_valid():
prod = form.save(commit=False)
prod.save()
return redirect('../thanks')
else:
form = ProductName()
context = {
'form': form
}
return render(request, "form_test.html", context)
def thanks_view(request):
query = Product_sell_create.objects.all()
return render (request, 'thanks.html', {'query' : query})
forms.py and models.py keeps the same
sell.html:
<h1> Upper test</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST2 </h1>
thanks.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ query }}</h1>
<h2>THANKS</h2>
</body>
</html>
did you create the 'sell.html' inside a 'templates' folder in your app folder?
MyApp/templates/sell.html

Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$']

I'm new learning Django and I want a study tracker web app with Django. The error came up when I was creating the function and template for new entries - this will allow a user write a detailed note about a topic they are currently learning about but whenever I run the template I get an error message:
Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P[0-9]+)/$'].
I've tried looking at the latest new_entry() function I wrote and tweak the topic variable name but the did not solve the issue. I also cross checked my url paths for any misspelling or whitespaces but there isn't. Here are my project files.
urls.py
from django.urls import path
from . import views
app_name = 'django_apps'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# Page that shows all topics.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic.
path('topics/<int:topic_id>/', views.topic, name='topic'),
# Page for adding a new topic.
path('new_topic/', views.new_topic, name='new_topic'),
# Page for adding a new entry.
path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),
]
views.py:
from django.shortcuts import render, redirect
from .models import Topic
from .forms import TopicForm, EntryForm
# Create your views here.
def index(request):
"""The home page for django app."""
return render(request, 'django_apps/index.html')
def topics(request):
"""Show all topic"""
topics_list = Topic.objects.order_by('id')
context = {'topics_list': topics_list}
return render(request, 'django_apps/topics.html', context)
def topic(request, topic_id):
"""Get topic and all entries associated with it."""
topic_list = Topic.objects.get(id=topic_id)
entries = topic_list.entry_set.order_by('-date_added')
context = {'topic_list': topic_list, 'entries': entries}
return render(request, 'django_apps/topic.html', context)
def new_topic(request):
"""Add a new topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('django_apps:topics')
# Display a blank name or invalid form.
context = {'form': form}
return render(request, 'django_apps/new_topic.html', context)
def new_entry(request, topic_id):
"""Add a new entry for a topic."""
topic_list = Topic.objects.get(id=topic_id)
if request.method != 'POST':
# NO data submitted; create a blank form.
form = EntryForm()
else:
# POST data submitted; process data.
form = EntryForm(data=request.POST)
if form.is_valid():
latest_entry = form.save(commit=False)
latest_entry.topic = topic_list
latest_entry.save()
return redirect('django_apps:topic', topic_id=topic_id)
# Display a blank name or invalid form.
context = {'topic_list': topic_list, 'form': form}
return render(request, 'django_apps/new_entry.html', context)
new_entry.html(updated!):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Study Tracker - Entry</title>
</head>
<body>
{% extends 'django_apps/base.html' %}
{% block content %}
{% for topic in topic_list %}
<p>{{ topic }}</p>
<p>Add a new entry:</p>
<form action="{% url 'django_apps:new_entry' topic_id=topic.id %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Add entry</button>
</form>
{% endfor %}
{% endblock content %}
</body>
</html>
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Base template</title>
</head>
<body>
<p>
Study Tracker -
Topics
</p>
{% block content %}{% endblock content %}
</body>
</html>
forms.py:
from django import forms
from .models import Topic, Entry
class TopicForm(forms.ModelForm):
"""A class that defines the form in which a user can enter in a topic."""
class Meta:
"""This class tells django which model to base the form on and the
fields to include in the form."""
model = Topic
fields = ['text']
labels = {'text': ''}
class EntryForm(forms.ModelForm):
"""A class that defines the form in which a user can fill in an entry to
a topic."""
class Meta:
"""This meta class tells django which model to base the form for
entries on and the fields to include in the form."""
model = Entry
fields = ['text']
labels = {'text': 'Entry:'}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
I do not know how to go about fixing this issue. I've checked all my inheritance urls and templates for errors but I can't figure out what seems to the problem.
Update: Here is my topic.html template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Study Tracker - Topic</title>
</head>
<body>
{% extends 'django_apps/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<p>
Add new entry
</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>There are currently no entries for this topic.</li>
{% endfor %}
</ul>
{% endblock content %}
</body>
</html>
I also checked the topic and entry ids in shell too.
You passed your template topic_list variable but in your template you used topic. I think you would set a loop. Because you have no any variable named topic. If you changed them, it will work.
Can you post the template of your topics/<int:topic_id>/ view? (django_apps/topic.html)
To me, it looks like you have in this template a {% url 'new_entry' %} without specifying a topic.id. Because your path for this view is 'new_entry/<int:topic_id>/', the reverse url is failing and you see this error.
You probably want to change {% url 'new_entry' %} to {% url 'new_entry' topic.id %} or something like that.
You seem to be passing an empty variable to the template
# Display a blank name or invalid form.
context = {'topic': topic, 'form': form} # Change the context variable
return render(request, 'django_apps/new_entry.html', context)
new_entry.html
...
{% block content %}
<p>{{ topic }}</p>
<p>Add a new entry:</p>
<form
action="{% url 'django_apps:new_entry' topic_id=topic.id %}"
method="post"
>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Add entry</button>
</form>
{% endblock content %}
...
Fixed it mate change your view.py file
add the parameter topic_id to your new_entry field
and a topic variable with Topic object
and topic in context
def new_entry(request, topic_id):
"""Add a new entry for a particular topic"""
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
# No data submitted, create a blank form
form = EntryForm()
else:
# POST data submitted, Process Data.
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.owner = request.user
new_entry.topic = topic
new_entry.save()
return redirect('logemys:topic', topic_id=topic_id)
# Display a blank or invalid form
context = {'topic': topic, 'form': form}
return render(request, 'logemys/new_entry.html', context)

Creating django form for related models

I have the following models defined:
class Question(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
question = models.CharField(max_length=200)
number_of_answers = models.IntegerField(default=0)
class Answer(models.Model):
question = models.ForeignKey(Question)
answer = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
I want the user to be able to create a question along with its corresponding answers.
Basically, I want to create a form that will ask the user to enter a question and the number of answers for the question. Based on the number-of-answers specified, I want to then create that many text fields for each answer. I want to be able to connect each answer to its corresponding question in the database.
What is the best way to do this in Python Django? I have provided images of what this would look like visually.
Getting question and number of answers,
getting answers based on question and number of answers specified
I would tackle this problem by using modelForms for creating questions, and then redirecting to a page where you can add the number of questions you specified when you created the question. This add_answers page won't use Django forms, we can just use a simple html form and then get the form data in the view. Here are the views:
views.py:
from django.shortcuts import render, redirect
from .forms import QuestionForm
from .models import Question, Answer
# Create your views here.
def add_question(request):
form = QuestionForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
question = form.cleaned_data.get('question')
number_of_answers = form.cleaned_data.get('number_of_answers')
create_question = Question.objects.create(question=question, number_of_answers=number_of_answers)
create_question.save()
return redirect('home:add-answers', id=create_question.id)
return render(request, 'home/add_question.html', {'form': form})
def add_answers(request, id):
question = Question.objects.get(id=id)
if request.method == "POST":
for i in request.POST.getlist('answers'):
_ = Answer.objects.create(answer=i, question=id)
_.save()
num_answers = question.number_of_answers
context = {"num_answers":range(num_answers), 'question':question}
return render(request, 'home/add_answers.html', context)
add_question uses model forms:
forms.py:
from django import forms
from .models import Question, Answer
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ['question','number_of_answers']
We can access this form in the template:
<form method="POST" action=".">
{{ form }}
{% csrf_token %}
<input type="submit">Submit</input>
</form>
For add_answers, we do the following:
<form method="POST" action=".">
{% for i in num_answers %}
<input type="text" name="answers"></input>
<br />
{% endfor %}
{% csrf_token %}
<input type="submit">Submit</input>
</form>
Where num_answers is a context variable that is range(number_of_answers).
Edit: here is the urls.py file:
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^add-answers/(?P<id>\d+)/$', views.add_answers, name="add-answers"),
url(r'^add-question/$', views.add_question, name="add-question"),
]
Have a look of formsets.And combine with django-dynamic-forms can help you custom a web page to add question with answer.
Here is a demo of add a team with it's player.
models.py
class Player(models.Model):
name = models.CharField(max_length=50)
score = models.IntegerField()
age = models.IntegerField()
def __str__(self):
return self.name
class Team(models.Model):
name = models.CharField(max_length=100)
players = models.ManyToManyField(Player)
def __str__(self):
return self.name
forms.py
from django import forms
from django.forms.formsets import formset_factory
from .models import *
class PlayerForm(forms.ModelForm):
class Meta:
model = Player
fields = '__all__'
PlayerFormset = formset_factory(PlayerForm)
class TeamForm(forms.Form):
name = forms.CharField()
players = PlayerFormset()
views.py
from django.shortcuts import render
from .forms import *
from .models import *
def post(request):
if request.method == 'POST':
form = TeamForm(request.POST)
player_instances = PlayerFormset(request.POST)
if form.is_valid():
if player_instances.is_valid():
team = Team(name=form.cleaned_data['name'])
team.save()
args = {'form': form}
for item in player_instances:
if item.is_valid():
player = item.save()
team.players.add(player)
else:
print('-----------error occur')
team.save()
return render(request, 'app1.html', args)
args = {'form': form}
return render(request, 'app1.html', args)
else:
form = TeamForm()
args = {'form': form}
return render(request, 'app1.html', args)
app1.html
<html>
<head>
<title>gffdfdf</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/static/jquery.formset.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="myForm" action="" method="post" class="">
{% csrf_token %}
<h2> Team</h2>
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} : {{ field }}
{% endfor %}
{{ form.players.management_form }}
<h3> Product Instance(s)</h3>
<table id="table-product" class="table">
<thead>
<tr>
<th>player name</th>
<th>highest score</th>
<th>age</th>
</tr>
</thead>
{% for player in form.players %}
<tbody class="player-instances">
<tr>
<td>{{ player.name }}</td>
<td>{{ player.score }}</td>
<td>{{ player.age }}</td>
</tr>
</tbody>
{% endfor %}
</table>
<button type="submit" class="btn btn-primary">save</button>
</form>
</div>
<script>
$(function () {
$('#myForm tbody tr').formset();
})
</script>
</body>
</html>
screen like:

Categories