简体   繁体   English

如何从Django中的模型创建下拉菜单

[英]How to create dropdown menu from model in django

I'm currently trying to create a drop-down menu for my Post categories in my base.html so that it gets displayed on every one of my templates. 我目前正在尝试在base.html中为我的帖子类别创建一个下拉菜单,以使其显示在我的每个模板上。 Later on, I want a user to simply click on a category item and get forwarded to the specific category. 稍后,我希望用户只需单击类别项目,然后转发到特定类别。

I'm a bit confused as to what I should include in my forms and how to call that form in my base.html. 我对应该在表单中包含什么以及如何在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: views.py:

from .forms import PostForm


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

models.py 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 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 context_processor.py

from .forms import PostForm

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

Thanks :) 谢谢 :)

Django will automatically make it a drop-down menu with your current form code. Django会自动将其设为包含您当前表单代码的下拉菜单。 You just need to make that form available using a context processor . 您只需要使用上下文处理器使该表单可用。

In your settings file, under templates, context_processors add something like `your_project.your_app.context_processors.category_form' 在设置文件的模板下,context_processors添加类似“ your_project.your_app.context_processors.category_form”的内容

And in your app (quickblog I believe) add a file: 并在您的应用中(我相信快速博客)添加一个文件:

context_processors.py context_processors.py

from .forms import PostForm

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

By the way, to reproduce your current code I had to make a few changes. 顺便说一句,要重现您的当前代码,我必须进行一些更改。

In views.py I changed categories = Category.objects.title() to categories = Category.objects.only('title') 在views.py中,我将categories = Category.objects.title()更改categories = Category.objects.title() categories = Category.objects.only('title')

and then got rid of that and just used the form instead 然后摆脱它,而是使用表格代替

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

And then finally to 然后终于

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

since the context_processor is now doing the work. 因为context_processor现在正在工作。


I believe in your comment you are asking how do you render just the drop-down. 我相信在您的评论中,您正在询问如何仅显示下拉列表。

In your template you'd do something like this: 在模板中,您将执行以下操作:

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

Please see Django's docs on the subject for more details. 有关更多详细信息,请参见Django的文档


Files I used to get it working 我用来使其正常工作的文件

models.py 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 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'
            ],
        },
    },
]
...

You can us some thing like this : 您可以给我们这样的东西:

Forms.py : Forms.py

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

Index.html : 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM