请帮助理解我应该在我的案例中使用哪种模式。
我在HTML模板中有下一个表单:
<div class="col-md-12">
<form id="developersform" action="#" method="post">
<select multiple="multiple" size="10" name="duallistbox_developers[]">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3" selected="selected">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
<option value="option6" selected="selected">Option 6</option>
<option value="option7">Option 7</option>
<option value="option8">Option 8</option>
<option value="option9">Option 9</option>
<option value="option0">Option 10</option>
</select>
<button type="submit" class="btn btn-default btn-block">Submit data</button>
</form>
</div>
查看无法处理到期状态问题:
if request.user.is_authenticated:
if request.method == 'POST':
form = ManagmentUsersForm(request.POST)
if form.is_valid():
picked = form.cleaned_data.get('duallistbox_guests')
print(picked)
else:
form = ManagmentUsersForm()
print(form.errors)
我应该如何在Django上指定表单?有人可以帮我举例 感谢
答案 0 :(得分:1)
要创建具有下拉列表的表单,请创建具有外键关系或多对多关系或其他内容的正确模型。在这里使用这些字段。
class ManagmentUsersForm(forms.ModelForm):
class Meta:
model = YOUR_MODEL
fields = [ 'duallistbox_guests'] #fields you want from your model
在您的视图中,您可以获取此数据并执行您想要执行的任何操作。
def YOUR_VIEW(request):
if request.method == 'POST':
if not request.user.is_authenticated:
return redirect('login')
else:
form = ManagmentUsersForm(request.POST, request.FILES)
if form.is_valid():
topic = form.cleaned_data.get("topic")
#grab your fields like this
user = request.user
YOUR_MODEL.objects.create(
User = request.user,
topic=topic,
#save them like this or do anything else
)
return redirect('SOMEWHERE') #successful
else:
if not request.user.is_authenticated:
return redirect('login')
else:
form = ManagmentUsersForm()
return render(request, 'YOUR_TEMPLATE', {'form': form})
您的HTML表单将是这样的
<form method="POST" enctype="multipart/form-data"> {% csrf_token %}
{{form.as_p}}
<input type = "submit" id="submit-question">
</form>