如何在django中从模型创建下拉菜单

时间:2018-05-29 20:31:03

标签: python django variables global

我目前正在尝试在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}

谢谢:)

2 个答案:

答案 0 :(得分:0)

Django将自动使用您当前的表单代码创建一个下拉菜单。您只需使用上下文处理器即可使该表单可用。

在您的设置文件中,在模板下,context_processors添加类似`your_project.your_app.context_processors.category_form'

的内容

在您的应用中(我相信quickblog)添加一个文件:

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

答案 1 :(得分:0)

你可以这样做:

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>