簡體   English   中英

模板中的 Django ModelForm

[英]Django ModelForm in template

我有一個問題。我是 Django 新手,學習了 3 周。 我需要為大學的一個項目開發一個帶有 optin 的 Cookie 彈出窗口。 我的問題是。 我在 Django python 中開發它。 在后端,我有收集所有 Cookie 信息並將其傳遞到 Cookie 模型的服務。 所以現在我有了 Cookie 模型,需要將它作為視圖中的上下文傳遞。 目前我看到服務在瀏覽器中收集的所有 Cookie。 但是我需要驗證 typ 是 Essential 還是 Marketing 並在模板的折疊中將其分開。 我怎么能做到這一點? 我的想法是用這一行在模板中驗證它

 {% if cookie.typ == 'Essenziell' %}

如果 typ 是 Essenziell,我會在折疊中顯示這一點。

查看.py

def optin(request):
if request.method == 'POST':
    form = CookieForm(request.POST)
    if form.is_valid():
        return HttpResponseRedirect
else:

    form = CookieForm
    cookie_list = Cookie.objects.all()

    context_dict = {'form': form, 'cookie_list': cookie_list}
    template = 'cookies/cookie.html'

return render(request, template,
    context_dict
              )

這是模板的一部分

<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#Marketing" aria-expanded="false" aria-controls="Marketing">
        Marketing
        </button>


        <div class="collapse" id="Essenziell">
        <div class="card card-body">
            {% for cookie in cookie_list  %}
                {% if cookie.typ == 'Essenziell' %}
                    <p>{{ cookie.cookie }}</p>
                    <p>{{ cookie.provider }}</p>
                    <p>{{ cookie.description }}</p>
                    <p>{{ cookie.typ }}</p>
                    <p>{{ cookie.runTime }}</p>
                {% endif %}
            {% endfor %}
        </div>
        </div>

模型.py

class Cookie(models.Model):
"""
:cookie: The defined name of the Cookie
:provider: Who will set this Cookie ex. Google, Matomo, Shopprovider
:description: The description of the seted Cookie
:cookieRuntime: The lifetime of the Cookie
:typ: Type of the Cookie
"""


cookie = models.CharField(max_length=50)
provider = models.CharField(max_length=100)
description = models.CharField(max_length=300)
typ = models.ForeignKey(Typ)

表單.py

class CookieForm(forms.ModelForm):
class Meta:
    model = Cookie
    field = {
        'cookie',
        'provider',
        'description',
        'typ',         
    }

您應該使用Serializers進行驗證和其他內容。 讀這個:

https://www.django-rest-framework.org/topics/html-and-forms/

為什么我需要序列化程序? 我不知道我應該使用它的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM