【问题标题】:How to create dropdown menu from model in django如何在 django 中从模型创建下拉菜单
【发布时间】:2018-05-29 20:31:02
【问题描述】:

我目前正在尝试在我的 base.html 中为我的帖子类别创建一个下拉菜单,以便它显示在我的每个模板上。 稍后,我希望用户只需单击一个类别项目并转发到特定类别。

对于我应该在我的表单中包含什么以及如何在我的 base.html 中调用该表单,我有点困惑。

base.html

...
<body>
        <div class="page-header">
            {% if user.is_authenticated %}
            <a href="{% url 'logout' %}" class="top-menu"><button type="button" class="btn btn-danger">Logout</button></a>
            <a href="{% url 'logout' %}" class="top-menu"><button type="button" class="btn btn-default">Account</button></a>
            <a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
            {% endif %}


            {% if user.is_anonymous %}
            <a href="{% url 'signup' %}" class="top-menu"><button type="button" class="btn btn-success">Sign-Up</button></a>
            <a href="{% url 'login' %}" class="top-menu"><button type="button" class="btn btn-primary">Login</button></a>
            {% endif %}

        <div class="fieldWrapper">
            <label for="{{ category_form.category.id_for_label }}">Select a category:</label>
            {{ category_form.category }}
        </div>

views.py:

from .forms import PostForm


def category_dropdown(request):
    return render (request, 'quickblog/base.html')

models.py

...
# Categorys of Post Model
class Category(models.Model):
    title = models.CharField(max_length=255, verbose_name="Title")
    description = models.TextField(max_length=1000, null=True)
    categorycover = fields.ImageField(upload_to='categorycovers/', blank=True, null=True, dependencies=[
        FileDependency(processor=ImageProcessor(
            format='JPEG', scale={'max_width': 600, 'max_height': 600}))
    ])

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']

    def __str__(self):
        return self.title

#Post Model
class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField(max_length=10000)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
    tag = models.CharField(max_length=50, blank=True)
...

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'text', 'category', 'tag', 'postcover', 'postattachment',]
    captcha = CaptchaField()

settings.py

...
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'quickblog.quickblog.context_processors.category_form',
)
...

context_processor.py

from .forms import PostForm

def category_form(request):
    form = PostForm()
    return {'category_form': form}

谢谢:)

【问题讨论】:

    标签: python django variables global


    【解决方案1】:

    Django 会自动将其设置为包含您当前表单代码的下拉菜单。您只需要使用 上下文处理器 使该表单可用。

    在您的设置文件中,在模板下,context_processors 添加类似“your_project.your_app.context_processors.category_form”的内容

    并在您的应用程序(我相信是快速博客)中添加一个文件:

    context_processors.py

    from .forms import PostForm
    
    def category_form(request):
        form = PostForm()
        return {'category_form': form}
    

    顺便说一句,为了重现您当前的代码,我必须进行一些更改。

    在views.py中 我把categories = Category.objects.title()改成了categories = Category.objects.only('title')

    然后摆脱它,只使用表单代替

    from .forms import PostForm
    def category_dropdown(request):
        form = PostForm()
        return render(request, 'quickblog/base.html', {'form': form})
    

    然后终于到了

    def category_dropdown(request):
        return render (request, 'quickblog/base.html')
    

    因为 context_processor 现在正在做这项工作。


    我相信您的评论是在询问您如何仅呈现下拉菜单。

    在你的模板中你会做这样的事情:

    <div class="fieldWrapper">
        <label for="{{ category_form.category.id_for_label }}">Select a category:</label>
        {{ category_form.category }}
    </div>
    

    更多详情请查看Django's docs on the subject


    我用来让它工作的文件

    models.py

    from django.db import models
    
    # Categorys of Post Model
    class Category(models.Model):
        title = models.CharField(max_length=255, verbose_name="Title")
        description = models.TextField(max_length=10000, null=True)
    
        class Meta:
            verbose_name = "Category"
            verbose_name_plural = "Categories"
            ordering = ['title']
    
        def __str__(self):
            return self.title
    
    #Post Model
    class Post(models.Model):
        author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
        title = models.CharField(max_length=200)
        text = models.TextField(max_length=10000)
        category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
    

    forms.py

    from django import forms
    from .models import Post
    class PostForm(forms.ModelForm):
        class Meta:
            model = Post
            fields = ['title', 'text', 'category']
    

    settings.py

    ...
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')]
            ,
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    'django_settings_export.settings_export',
                    'quickblog.context_processors.category_form'
                ],
            },
        },
    ]
    ...
    

    【讨论】:

    • 嘿,谢谢你的更新,但是如何显示???
    • 我更新了我的回复。如果有帮助,请选择它作为答案。如果不是,请在后续问题中说明您要问的问题。
    • 我刚刚用一些额外的东西更新了我的问题......我现在唯一看到的是 basr.html 显示标签:“选择一个类别:”但之后没有下拉菜单......我错过了什么吗?
    • 它对我有用,我必须仔细检查你的代码。数据库中有一些内容吗?
    • 我检查过的一切都正常。你可以在没有验证码的情况下尝试吗?另外,我正在尝试不带标签和类别封面字段,因为我没有这些模型。
    【解决方案2】:

    你可以给我们一些这样的东西:

    Forms.py

        class MyModel2(forms.Form):
             color = forms.CharField(widget=forms.Select)
    

    Index.html

    <form method="POST" action = "ACTION_OR_VIEW_URL_ON_SUBMIT_HERE">{% csrf_token %}
        <label for="colorSelect">Choose color</label>
        <select type="text" id="colorSelect" name="colorSelect">
            <option selected>GREEN</option>
            <option>BLUE</option>
            <option>RED</option>
            <option>ORANGE</option>
            <option>BLACK</option>
        </select>
        <br><br>
        <input type="submit" value="Submit!"/>
    </form>
    

    【讨论】:

    • 是的,但问题是我从数据库中获取了我的价值,这就是为什么这个解决方案不适合 4 个我
    猜你喜欢
    • 2021-10-01
    • 2015-09-16
    • 1970-01-01
    • 2017-08-11
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2012-11-08
    相关资源
    最近更新 更多