我想实现一个选择框,用户可以在其中选择适当的选项,然后在保存之前将其“转移”到“选定的框”中。 Django在管理界面中具有此功能,就像在post中一样,但是如何在普通网站中实现呢?欢迎链接到relevent教程或基于te的示例。
这是我用于多对多关系托管表的模型。
# models.py
class Container(models.Model):
container_id = models.AutoField(primary_key=True)
location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT)
icon_desc = models.ForeignKey(Icon, db_column='icon_desc', null=True, blank=True, default='Box',on_delete = models.PROTECT)
container_name = models.CharField(max_length=50, blank=True, null=True)
class Sample(models.Model):
sample_id = models.AutoField(primary_key=True)
containers = models.ManyToManyField(Container, through='JoinSampleContainer', through_fields=('sample_id', 'container_id'), related_name='sample')
class JoinSampleContainer(models.Model):
id = models.AutoField(primary_key=True)
sample_number = models.IntegerField()
container_id = models.ForeignKey(Container, db_column='container_id', on_delete = models.PROTECT)
sample_id = models.ForeignKey(Sample, db_column='sample_id', on_delete = models.PROTECT)
在Views.py中,我需要进行常规表单设置:
def assignsample(request):
if request.method == "POST":
form = AssignForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('alldepotsamples')
else:
form = AssignForm()
return render(request, 'depotsample/assignsample.html', {'form': form})
表格:
class AssignForm(forms.ModelForm):
class Meta:
model = Sample
fields = (
'sample_id',
'containers'
)
使用占位符在html中显示:
{{ form.sample_id}}
{{ form.containers}}