Home python How dynamically you can create forms

How dynamically you can create forms




How dynamically you can create forms in Django and add to the database later, I would like to know an exemplary sequence of actions and is it possible if this is possible using this library

Answer 1, Authority 100%

In Django, when saving data in the database, it is understood that you will use models.
Based on the description of your model, Django creates tables in the database. Correspondingly, if you want to record arbitrary data in the database without a preliminary description of the models, then this is contrary to the basic concept of Django. But if you really want to use Django forms and templates for organizing user entering, you can relate a little. For example, somehow so

from django import forms
from django.db Import Connection
Class MyForm (Forms.form):
  Type_map = {
    'str': Forms.charfield (), # for example, I will use only string and integer fields
    'int': Forms.integerfield (),
  Def __init __ (Self, * Args, ** kwargs):
    self.table_name = kwargs.pop ("Table_Name")
    self.field_list = kwargs.pop ("field_list", {})
    Super () .__ init __ (* Args, ** kwargs)
    Field_Name, Field_Definition in Self.field_list.Items ():
      Created_Field = MyForm.Type_Map [Field_Definition ["Type"]]
      Created_Field.Required = Field_Definition.get ('Required', False)
      Created_Field.Label = Field_Definition.get ('Label', "Field_Name")
      self.fields [Field_Name] = Created_Field
    SQL_INSERT_TEMPLATE = "INSERT INTO {} ({}) Values ​​({})"
    Fields = ""
    Values ​​= ""
    FIELD_NAME, FIELD_VALUE IN SELF.cleaned_Data.Items ():
      IF Fields:
        Fields + = ','
        Values ​​+ = ','
      Fields + = field_name
      Values ​​+ = '"{}". Format (field_value)
    Complete_SQL = SQL_INSERT_TEMPLATE.Format (Self.table_name, Fields, Values)
    Return Complete_SQL # for tests made Return SQL string
    With Connection.cursor () As Cursor:
      Cursor.Execute (SQL_INSERT_TEMPLATE.Format (Complete_SQL))

Then creating a form in us should be with the transfer of all necessary parameters
In your case, the field_list will not be permanent, and you will form it on the basis of data entered by user, weather, day of the week, in general, what will wish

new_form = myForm (
  table_name = "my_table",
  field_list = {
    'first_field': {'Type': 'str'},
    'Second': {'type': 'int', 'order': true, 'label': 'age'}

Print (new_form) will give such a result

& lt; tr & gt; & lt; th & gt; & lt; label for = "id_first_field" & gt; field_name: & lt; / label & gt ; & lt; / th & gt; & lt; TD & GT; & lt; Input Type = "text" name = "first_field" value = "test_str" id = "id_first_field" / & gt; & lt; / td & gt; & lt; / tr & gt;
& lt; tr & gt; & lt; th & gt; & lt; label for = "id_second" & gt; age: & lt; / label & gt; & lt; / th & gt; & lt; td & gt; & lt; input type = "Number" name = "Second" Value = " 91 "ID =" ID_SECOND "REQUIRED / & GT; & lt; / td & gt; & lt; / tr & gt;

Check how the form behaves when receiving data and the resulting SQL

new_form = myForm (
      {'first_field': 'test_str', 'second': 121},
      table_name = "my_table",
      field_list = {
        'first_field': {'Type': 'str'},
        'Second': {'type': 'int', 'order': true, 'label': 'age'}

form.is_valid () will give us true and form.save () will return to us SQL request to create a record in the table.

'insert into my_table (first_field, second) Values ​​("test_str", "121")'

We can also transmit the form of the value entered by the user (request.post ), check the validity and save to the database if all data is correct

For example in View

def save_my_extraordinary_data (Request):
  new_form = MyForm (
    Request.post or none
    table_name = "my_table",
    field_list = {
      'first_field': {'Type': 'str'},
      'Second': {'Type': 'int', 'Required': True, 'MIN': 100
  If Request.post:
    IF new_form.is_valid ():
      new_form.save ()
      Redirect ('New Url')
  Render (Request, "Template_name.html", {'Form': New_form})

But it must be borne in mind that it will still have to bypass some underwater stones:
The name of the fields in the database can be reserved words in Python and their minds also need to be transmitted by a separate field and process it. Also, the obtained values ​​must be processed in more detail (for example, the rows remove dual quotes), as well as protect against SQL injections. It is also necessary to be freeze with the processing of the required restrictions on the fields where it will be necessary (for example, the integer must be more than 100 and less than 200, or checks on the uniqueness of the field).

If, under dynamic forms, you meant that you have several models and you need that Django, depending on some conditions created you for a form for a particular model in the quantities you need, then yes, here it will be just enough

If you are going to add a button to press the button on the page, one of the options –

Forming HTML with the type of form that you need, but form the CSS class, which will not display it on the page (for example, .hidden ). And when you click on the button to create a new form, clone it, you remove the CSS class Hidden and add to the page (all this is done either with jQuery or pure javascript). And you all have a new form for data entry ready.

If you need to simultaneously be sent not one form and immediately a few, then look in the direction of FormSet https://docs.djangoproject.com/en/3.1/topics/Forms/FormSets/#formSets
As an option to see how the admin is made by Django, create two models. The second model makes the ForeignKey link on the first. Then you register both models in the admin. Second model as inline.
You can make an example from the documentation to take https: // docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.tabularinline , then you go to the administrator you choose editing the first model and you look at how Django forms HTML and do something like this

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions