简体   繁体   English

基于 model 多选字段在模板 django 中显示结果

[英]Based on model multiselectfield show result in template django

based on multiple choice field i want to show result in template but I have no idea how to do as you can see in this model i give lunch choice to students base on lunch choice i want to show result but it is not working for ex if he select sandwich the result after submit will you sandwich will be ready and same for others基于多项选择字段,我想在模板中显示结果,但我不知道该怎么做,正如您在此 model 中看到的那样,我根据午餐选择为学生提供午餐选择我想显示结果,但它不适用于 ex if他 select 三明治提交后的结果你的三明治会准备好和其他人一样吗

from multiselectfield import MultiSelectField
class student(models.Model):
    lunch_choice = [ 
        ('Sandwich', 'Sandwich'),
        ('Salad', 'Salad'),
        ('omlete', 'omlete'),
    ]
    name = models.CharField(max_length=70, blank=False)
    classs =  models.CharField(max_length70, blank=True)
    lunch =  MultiSelectField(choices=lunch_choice, blank=True)

    def __str__(self):
        return self.name

i tried in my HTML and it didn't work我在我的 HTML 中试过,但没有用

{% if student.classs %}
{% if student.lunch == 'Sandwich' %}
          <p> your sandwich will be ready</p>
{% endif %} 
{%endif%}

and in form.py using widget并在 form.py 中使用小部件

widgets = {
    'lunch':forms.CheckboxSelectMultiple(attrs={'id':'lunch'}),
}

my views.py我的意见.py

def preview(request):
    student = student.objects.all()
    return render(request, 'preview.html',{'student':student})

OP can create a model for lunches (it would enable to create new lunches, edit and delete). OP 可以为午餐创建一个 model(它可以创建新的午餐,编辑和删除)。 Then, in the Student model create a lunch with a ManyToManyField , like然后,在 Student model 中使用ManyToManyField创建午餐,例如

lunch = models.ManyToManyField(Lunch, blank=True)

Note the usage of blank=True to not require the field in the forms.注意使用blank=True不需要 forms 中的字段。

Then, when one generates a form based on that model, it'll create an experience just like the one in Django Admin where one can select multiple ones.然后,当一个基于 model 的表单生成一个表单时,它会创建一种类似于 Django Admin 中的体验,其中一个可以 select 多个。

One can then show it to the user in a template .然后可以在模板中向用户展示它


If one doesn't like the experience of the form and want to make it more user friendly, there are some articles out there explaining that如果一个人不喜欢表单的体验并希望使其更加用户友好,那么有一些文章解释了这一点

This happens because the string is being compared to type: type(aaa[0].lunch) <class 'multiselectfield.db.fields.MSFList'>.发生这种情况是因为字符串正在与类型进行比较:type(aaa[0].lunch) <class 'multiselectfield.db.fields.MSFList'>。 Printed the data type 'type(aaa[0].lunch)' of the first value from the database in the view.打印视图中数据库中第一个值的数据类型“type(aaa[0].lunch)”。 Used stringformat:'s' to convert data to string in template.使用 stringformat:'s' 将数据转换为模板中的字符串。 Here you can read about the conversion: conversion在这里您可以阅读有关转换的信息: conversion

transformation type:转换类型:

replace 'samplesite' with the name of your application.将“samplesite”替换为您的应用程序的名称。

urls.py网址.py

urlpatterns = [
   path("Test/", Test, name = 'Test'),
]

views.py视图.py

def Test(request):
    aaa = student.objects.all()
    print('type(aaa[0].lunch)', type(aaa[0].lunch))
    context = {'fff': aaa}

    return render(request, 'samplesite/lunch.html', context)

lunch.html午餐.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
</head>
<body>
    {% for aa in fff %}
    {% if  aa.lunch|stringformat:'s' == 'Sandwich' %}
    <p>{{aa.lunch}}</p>
    <p>{{aa.name}}</p>
    {% endif %}
    {% endfor %}
</body>
</html>

settings in settings.py: settings.py 中的设置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }

django version 4.1 django 4.1版在此处输入图像描述

acc to me there is no such way by which u can show the result base on selected option because i also tried to use that and look for answers on internet but didn't find anything and creator of that repo is also not responding although I would recommend you to use models many to many field It will allow user to select more than one option like multiselectfield like this对我来说,没有这样的方法可以根据所选选项显示结果,因为我也尝试使用它并在互联网上寻找答案,但没有找到任何东西,并且该回购协议的创建者也没有回应,尽管我会建议您使用模型多对多字段它将允许用户使用 select 多个选项,例如这样的多选字段

first, create models首先,创建模型

class Lunch(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

then add this in student models然后将其添加到学生模型中

lunch =  models.ManyToManyField(Lunch, blank=True, related_name="lunch")

then add your option in lunch model然后在午餐 model 中添加您的选项

and it in your template to show result base on selected option并在您的模板中显示基于所选选项的结果

{% if student.classs %}
{% for Lunch in student.lunch.all %}
{% if Lunch.title == 'Sandwich' %}
          <p> your sandwich will be ready</p>
{% endif %}
{% endfor %} 
{%endif%}

it will work它会起作用的

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

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