在Django中,如何创建一个不使用数据库的独立组合框?

huangapple go评论59阅读模式
英文:

In Django, how can I create a independent combobox that doesn't use the database?

问题

以下是您要翻译的内容:

forms.py

from django import forms

FAVORITE_COLORS_CHOICES = [
    ("blue", "Blue"),
    ("green", "Green"),
    ("black", "Black"),
]

class SimpleCombobox(forms.Form):
    favorite_colors = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=FAVORITE_COLORS_CHOICES,
    )

app1/views.py

from django.shortcuts import render, redirect
from app1.forms import SimpleCombobox

def app1(request):
    return render(request, 'app1/index.html')

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})

app1/urls.py

from django.urls import path
from . import views
from app1.views import index

urlpatterns = [
    path('', views.app1),
    path('', index, name='index'),
]

index.html

...
<body>
    <form method="post">
        {% csrf_token %}
        {{form}}
        <button type="submit">
            submit
        </button>
    </form>
</body>
...

mysite (project)/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app1/', include('app1.urls')),
    path('', include('app1.urls'))
]

settings.py

TEMPLATES = [
    {
        ...
        'DIRS': [ BASE_DIR / 'templates' ],
        ...
    },
]

请注意,这些内容已经翻译成中文,如果您需要进一步的帮助或解释,请告诉我。

英文:

I'm new in world Django. In my index.html page, I would like to insert a simple combobox that won't be connected to the database, but will be independent, for building miscellaneous code.

There is something wrong. I don't see the combobox and the index page doesn't open. What should I write in forms.py, view.py, models.py, urls.py, index.html and elsewhere? Thank you all!

forms.py

from django import forms

FAVORITE_COLORS_CHOICES = [
    (&quot;blue&quot;, &quot;Blue&quot;),
    (&quot;green&quot;, &quot;Green&quot;),
    (&quot;black&quot;, &quot;Black&quot;),
]


class SimpleCombobox(forms.Form):
    favorite_colors = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=FAVORITE_COLORS_CHOICES,
    )

app1/views.py

from django.shortcuts import render, redirect
from app1.forms import SimpleCombobox #Creato per Combobox


def app1(request):
    return render(request, &#39;app1/index.html&#39;)


def index(request):
    if request.method == &quot;POST&quot;:
        form = SimpleCombobox(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            # Output Sample
            # {&#39;favorite_colors&#39;: [&#39;blue&#39;, &#39;green&#39;]}
            return redirect(&quot;index&quot;)

    else:
        form = SimpleCombobox()

    return render(request, &quot;index.html&quot;, {&quot;form&quot;: form})

app1/urls.py

from django.urls import path
from . import views

from app1.views import index #Aggiunto per combobox

urlpatterns = [
    path(&#39;&#39;, views.app1),
    path(&#39;&#39;, index, name=&#39;index&#39;),
]

index.html

...
&lt;body&gt;
    &lt;form method=&quot;post&quot;&gt;
        {% csrf_token %}
        {{form}}
        &lt;button type=&quot;submit&quot;&gt;
            submit
        &lt;/button&gt;
    &lt;/form&gt;
&lt;/body&gt;
...

mysite (project)/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path(&#39;admin/&#39;, admin.site.urls),
    path(&#39;app1/&#39;, include(&#39;app1.urls&#39;)), #si occuper&#224; di gestire tutti i link dell&#39;app app1
    path(&#39;&#39;, include(&#39;app1.urls&#39;)) #Aggiunto per Combobox
]

settings.py

I also tried not to put it, so I also tried to leave &#39;DIRS&#39;: [] by default: the page still opens without problems

TEMPLATES = [
    {
        ...
        &#39;DIRS&#39;: [ BASE_DIR / &#39;templates&#39; ],
        ...
    },
]

答案1

得分: 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 an 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 set up your templates correctly in settings.py (for instance):

TEMPLATES = [
    {
        ...
        'DIRS': [BASE_DIR / 'templates'],
        ...
    },
]

And have a running server, you should be good to go!

英文:

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 == &quot;POST&quot;:
        form = SimpleCombobox(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            # Output Sample
            # {&#39;favorite_colors&#39;: [&#39;blue&#39;, &#39;green&#39;]}
            return redirect(&quot;index&quot;)

    else:
        form = SimpleCombobox()

    return render(request, &quot;index.html&quot;, {&quot;form&quot;: form})

myapp/urls.py

from django.urls import path
from myapp.views import index

urlpatterns = [
    path(&#39;&#39;, index, name=&#39;index&#39;)
]

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

...
&lt;body&gt;
    &lt;form method=&quot;post&quot;&gt;
        {% csrf_token %}
        {{form}}
        &lt;button type=&quot;submit&quot;&gt;
            submit
        &lt;/button&gt;
    &lt;/form&gt;
&lt;/body&gt;
...

Then include myapp.urls setup to the root urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path(&#39;admin/&#39;, admin.site.urls),
    path(&#39;&#39;, include(&#39;myapp.urls&#39;))
]

If you have setup your templates correctly at settings.py (for instance):

TEMPLATES = [
    {
        ...
        &#39;DIRS&#39;: [ BASE_DIR / &#39;templates&#39; ],
        ...
    },
]

And have a running server, you should be good to go!

huangapple
  • 本文由 发表于 2023年6月15日 12:32:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定