1👍
✅
Your form is okay. If you are not going to persist data then you do not need to use Django models
. The only thing you need to do is create a instance of this form and render it.
Suppose we create and app
called myapp
. There you have your files, such as forms
, views
, urls
, etc.
myapp/views.py
from django.shortcuts import render, redirect
from myapp.forms import SimpleCombobox
def index(request):
if request.method == "POST":
form = SimpleCombobox(request.POST)
if form.is_valid():
print(form.cleaned_data)
# Output Sample
# {'favorite_colors': ['blue', 'green']}
return redirect("index")
else:
form = SimpleCombobox()
return render(request, "index.html", {"form": form})
myapp/urls.py
from django.urls import path
from myapp.views import index
urlpatterns = [
path('', index, name='index')
]
Note that you can also use relative imports
(e.g. from .forms import SimpleCombobox
). Although in my example I am using absolute imports.
index.html
...
<body>
<form method="post">
{% csrf_token %}
{{form}}
<button type="submit">
submit
</button>
</form>
</body>
...
Then include
myapp.urls
setup to the root urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls'))
]
If you have setup your templates correctly at settings.py
(for instance):
TEMPLATES = [
{
...
'DIRS': [ BASE_DIR / 'templates' ],
...
},
]
And have a running server, you should be good to go!
👤Niko
Source:stackexchange.com