gpt4 book ai didi

python - 如何在 Django FileField/CharField/BooleanField/Upload 按钮上使用 Bootstrap

转载 作者:行者123 更新时间:2023-11-28 03:51:16 24 4
gpt4 key购买 nike

我有以下 Django 设置。

模型.py
class Method1(models.Model):
inputfile_param = models.FileField()
species_param = models.CharField(max_length=20, choices=(('mouse', 'Mouse'), ('human','Human')))
norm_mode_param = models.CharField(max_length=20, choices=(('genecount_norm', 'Gene Count'), ('totalscore_norm','Total Score')))
logscale_param = models.BooleanField(default=False)

View .py
from .forms import Method1Form
def method1_input(request):
if request.method == 'POST':
form = Method1Form(request.POST, request.FILES)
# Handle file upload
if form.is_valid():
q = form.save()
q.save()
# This is where we run code
# with the given parameters
q.run_code1()

# This will show the method1_result to be executed.
return HttpResponseRedirect(reverse('method1-result', kwargs={'id': q.id }))

else:
form = Method1Form()

return render(request, 'mycool_app/method1.html', {'form':form})

表单.py
from .models import Method1
class Method1Form(forms.ModelForm):
class Meta:
model = Method1
# Exclude means what not to show
# when form is displayed
exclude = ['state','clustering_state','ip_address','creationtime']

HTML

设置mycool_app/method1.html文件:

<!DOCTYPE html>
<html>
<body>
<form action="{% url 'method1-input' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p> {{form.inputfile_param.errors}} </p>
<p> {{form.inputfile_param}} </p>
<p> {{form.species_param }} </p>
<p> {{form.norm_mode_param }} </p>
<p> Log-scaling {{form.logscale_param}}</p>

<p><input type="submit" value="Upload" /></p>
</body>
</html>

最后看起来像这样:

enter image description here

我想用 Bootstrap 渲染它。我该怎么做?

最佳答案

你需要在你的表单中这样做

像这样:

表单.py

state_list = State.objects.filter().order_by('name')

class MyForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)

self.fields['state'] = forms.ModelChoiceField(
required=True,
error_messages={'required': 'State / Province is Required!'},
label='State',
widget=forms.Select(attrs={
'class': 'form-control dropdown-toggle input-lg',
'data-toggle': 'dropdown',
'aria-expanded': 'false',
'role': 'menu',
'required': 'required',
'oninvalid': "this.setCustomValidity('State / Province is Required!')",
'onchange': "this.setCustomValidity('')",
}),
queryset=state_list,
empty_label='Select State / Province',
)

.... more fields

class Meta:
model = MyModel
fields = [
'myfield',
]

template.html

<div class="form-group">
<label for="state" class="col-sm-4 control-label">State</label>
<div class="col-sm-8">
{{ form.state }}
</div>
</div>

您可以看到在 Bootstrap 中完成的相同渲染 Django 表单 here

关于python - 如何在 Django FileField/CharField/BooleanField/Upload 按钮上使用 Bootstrap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32856564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com