Answer the question
In order to leave comments, you need to log in
How to create dynamic forms in django?
I'm building a web application for my hand-to-hand combat club and doing development in Django for the first time.
I have models that I have migrated to the database. The database contains information on each member of the club.
models.py
class Post(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
adult = models.BooleanField(default=False)
class CreateForm(forms.Form):
firstname = forms.CharField(max_length=60, label="Укажите имя ")
lastname = forms.CharField(max_length=60, label="Укажите фамилию ")
def index(request):
createForm = CreateForm()
if '_okcreatet' in request.POST:
firstname = request.POST.get("firstname ")
lastname = request.POST.get("lastname")
adult = request.POST.get("adult ")
b = Post(firstname='%s' % firstname, lastname='%s' % lastname) # Внос данных в бд
b.save()
if '_okupdate' in request.POST:
return HttpResponseRedirect('/tariff/')
else:
return render(request, "index.html", {"form": createForm)
<body>
<form method="POST">
{% csrf_token %}
<table>
{{form}}
</table>
<td><input name="_okcreatet" type="submit" value="OK"></td>
<td><input name="_okupdate" onclick="location.href='{% url 'update' %}'" type="submit" value="OK"></td>
{% block content %}
{% endblock %}
</form>
{% extends 'index.html' %}
{% block content %}
<form method="POST">
{% csrf_token %}
<table>
<!--{{form}}--> <!--На этом месте должны создаваться формы-->
</table>
<td><input name="_okclick" type="submit" value="OK"></td>
</form>
{% endblock %}
urlpatterns = [
url(r'^$', views.index),
url(r'^update/$', views.updt, name='update'),
]
Answer the question
In order to leave comments, you need to log in
1. it is better to inherit the form from ModelForm: https://djbook.ru/rel1.9/topics/forms/modelforms.html
2. to do it the way you want, I would create a list (array) of forms in the View for each records (model instance), would give them to the template, and then display them in a cycle in a separate form <form>
. you also need to somehow give an id in each form, either as a hidden field or in the URL. to make it convenient to operate all of this from the point of view of the end user, it is worth screwing AJAX.
3. if you are just learning Django, it’s better to forget about your idea (edit everything from one page) for a while and write the simplest, most straightforward CRUD: separate View for the list of posts, for creating a post, for viewing and editing a post. when you work out the skills, then it will be possible to have a bunch of forms on one page, and AJAX, and everything else.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question