在相关模型上创建多个select (在CreateView上)到一个外键的方法有以下几种:
from django import forms
from django.views.generic.edit import CreateView
from .models import Model1, Model2
class MyForm(forms.ModelForm):
class Meta:
model = Model1
fields = '__all__'
model2_1 = forms.ModelChoiceField(queryset=Model2.objects.all(), label='Model2 1')
model2_2 = forms.ModelChoiceField(queryset=Model2.objects.all(), label='Model2 2')
class MyCreateView(CreateView):
model = Model1
form_class = MyForm
template_name = 'my_template.html'
success_url = '/success/'
def form_valid(self, form):
# 处理表单提交
return super().form_valid(form)
from django.views.generic.edit import CreateView
from .models import Model1, Model2
class MyCreateView(CreateView):
model = Model1
fields = '__all__'
template_name = 'my_template.html'
success_url = '/success/'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['model2_objects'] = Model2.objects.all()
return context
<!-- my_template.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<label for="id_model2_1">Model2 1:</label>
<select id="id_model2_1" name="model2_1">
{% for model2_obj in model2_objects %}
<option value="{{ model2_obj.pk }}">{{ model2_obj }}</option>
{% endfor %}
</select>
<label for="id_model2_2">Model2 2:</label>
<select id="id_model2_2" name="model2_2">
{% for model2_obj in model2_objects %}
<option value="{{ model2_obj.pk }}">{{ model2_obj }}</option>
{% endfor %}
</select>
<button type="submit">Submit</button>
</form>
以上两种方法可以根据具体情况选择适合的方式来实现在相关模型上创建多个选择框(select)到一个外键。根据需求和场景的不同,选择相应的方法进行实现。对应的腾讯云产品可以参考腾讯云的云服务器CVM(https://cloud.tencent.com/product/cvm)、弹性伸缩Auto Scaling(https://cloud.tencent.com/product/as)、云数据库MySQL(https://cloud.tencent.com/product/cdb_mysql)、对象存储COS(https://cloud.tencent.com/product/cos)等。
领取专属 10元无门槛券
手把手带您无忧上云