Django:如何根据输入值添加输入元素以形成表单

时间:2019-06-14 07:23:57

标签: django ajax django-forms

我有一个来自以下模型的Django表单:

public bool CreateNewUser(string name, string password, string host)
{
   string query = "CREATE USER $name@$host IDENTIFIED BY $password;";
   List<MySqlParameter> mies = new List<MySqlParameter>
   {
      new MySqlParameter("$name", name),
      new MySqlParameter("$password", password),
      new MySqlParameter("$host", host)
   };

   return InsertIntoQuery(query, mies);
}

//The InsertIntoQuery looks like this

private bool InsertIntoQuery(string sql, List<MySqlParameter> sqlParameters = null)
{
   bool retBl = false;
   try
   {
      using (var SqlConnection = new MySqlConnection(ConnectionStr))
      {
         SqlConnection.Open();
         using (var cmd = new MySqlCommand(sql, SqlConnection))
         {
            if (sqlParameters != null)
               foreach (var item in sqlParameters)
                  cmd.Parameters.AddWithValue(item.ParameterName, item.Value);
            cmd.Prepare();
            var retValNonQuery = cmd.ExecuteNonQuery();

            retBl = (retValNonQuery > 0) ? true : false;
         }
      }
   }
   catch (Exception e)
   {
      MessageBox.Show("Error: " + e.Message);
   }
   return retBl;
}

模型形式:

class Ledger1(models.Model):
    ledger_name     = models.CharField(max_length=32)
    group1_name     = models.ForeignKey(Group1,on_delete=models.CASCADE,null=True,related_name='ledgergroups') 
    taxes           = (
        ('GST','GST'),
        ('Others','Others'),
        )
    tax_type        = models.CharField(max_length=100,choices=taxes,default='GST',blank=True)

我想以这样的方式创建表单:class Ledgerform(forms.ModelForm): class Meta: model = Ledger1 fields = ('ledger_name', 'group1_Name','tax_type') def __init__(self, *args, **kwargs): super(Ledgerform, self).__init__(*args, **kwargs) self.fields['ledger_name'].widget.attrs = {'class': 'form-control',} self.fields['group1_name'].widget.attrs = {'class': 'select2_demo_2 form-control', 'placeholder':"Select Group",} self.fields['tax_type'].widget.attrs = {'class': 'form-control',} 字段将隐藏在前端,并且仅当用户从tax_type中选择tax时才可见字段ForeignKey

group1_name对象是通过信号自动创建的。

不是ajax的专业人士,因此在解决该问题时遇到了一些困难。

任何解决方案都会对我的学习过程有所帮助。

谢谢

0 个答案:

没有答案