django 在定义的CharField中合并form.model中的两个值

fjaof16o  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(102)

我尝试将下拉菜单中的两个值合并到HTML输入字段中
model.py

class ProjectID(models.Model):
    project_id = models.CharField(max_length=120, unique=True)

    def __str__(self):
        return self.project_name

class ProjectName(models.Model):
    project_name = models.CharField(max_length=120, unique=True)

    def __str__(self):
        return self.project_name

class Project(models.Model):
    combine_name = models.CharField(max_length=50, unique=True)
    project_id = models.ForeignKey(ProjectID,
                                   related_name='p_number',
                                   on_delete=models.CASCADE)
    project_name = models.ForeignKey(ProjectName,
                                     related_name='p_name',
                                     on_delete=models.CASCADE)  

    def __str__(self):
        return f"{self.project_id}_{self.project_name}"

字符串
views.py

class AddProject(generic.FormView):
    template_name = 'project/project-add.html'
    form_class = ProjectAddForm
    success_url = reverse_lazy('project:project-dashboard')


urls.py

urlpatterns = [
    path('', views.dashboard, name='project-dashboard'),
    path('add/', views.AddProject.as_view(), name='project-add')
]


网址:forms.py

class ProjectAddForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ['project_id', 'project_name', 'combine_name']


project-add.html

{% block main-body %}
<div class="container">
  <form method="post" class="form card p-3 mt-5">
    {% csrf_token %}
    <div class="row align-items-start">
      <div class="col-md-4" id="option_a">
        {{ form.project_id|as_crispy_field }}
      </div>
      <div class="col-md-4" id="option_b">
        {{ form.project_name|as_crispy_field }}
      </div>
    </div>
    <div class="row align-items-center">
      <div class="col-md-8">{{ form.combine_name|as_crispy_field }}</div>
    </div>

{% endblock main-body %}


如果下拉菜单被选中并显示在字段form.combine_name中,我尝试合并form.project_idform.project_name
使用jquery的结果失败了,因为我猜它不可能使用模板标签来处理

$('#option_a, #option_b').change(function() {
   var val = $('#option_a').val() + $('#option_b').val(),
             new_price;
   $("#new_option").text(val);

lf3rwulv

lf3rwulv1#

为什么需要合并_name字段?看起来它所要做的就是显示另外两个字段的组合字符串。这些字段已经在数据库中,因此复制它们没有意义。我会把那些田地都处理掉。
您已经使用str方法动态创建了值。为什么要分开保存呢?

相关问题