需要有关FilteredSelectMultiple小部件的指导 [英] Need guidance with FilteredSelectMultiple widget

查看:71
本文介绍了需要有关FilteredSelectMultiple小部件的指导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,这个问题可能会变得不太广泛,但是由于我只是在学习django(而且我只是业余爱好者开发人员),因此我需要一些指导,希望对以后像我这样的人有所帮助找不到有关使用此小部件的任何清晰易懂的指南。有了您的答案和帮助,我将尝试使该问题至少具有指导意义。

I am sorry if it question might turn to be little broad, but since I am just learning django (and I am just hobbyist developer) I need some guidance which, I hope, will help someone like me in the future since I could not find any clear and easily comprehensible guide on using this widget. With your answers and help I will try to make this question thread at least guide-ish.

材料对于该主题,我发现有些帮助:

Material I found somewhat helpful for this topic:

Django多项选择小部件?

Django:替换为表单的默认ManyToMany窗口小部件

Django的FilteredSelectMultiple小部件仅在登录时有效

未在页面上呈现的Django FilteredSelectMultiple

使用形式的Django管理应用程序的FilteredSelectMultiple小部件

从Django中的FilteredSelectMultiple小部件中获取所选值

Django FilteredSelectMultiple右半部分不渲染

有其他链接很少,但是它们没有使任何内容更清晰或添加新信息,因此我不会提及它们。

There were few others links, but they did not made anything clearer or added new information so I won't mention them.

这是我设法理解的(请纠正我)如果我错了或添加我错过的任何内容):

Here is what I managed to understand (please correct me if I am wrong or add anything that I missed):

要创建 FilteredSelectMultiple 小部件冷杉,我需要修改 forms.py (与其他任何小部件创建过程一样)。修改后的 forms.py 应该具有django.contrib.admin.widgets中的 import FilteredSelectMultiple import和媒体类。 forms.py 代码应如下所示(请纠正我,因为在某处可能是错误的):

To create FilteredSelectMultiple widget firs I need to amend forms.py (as in any other widget creation process). Amended forms.py should have from django.contrib.admin.widgets import FilteredSelectMultiple import and Media class. forms.py code should look like this (please correct me, because probably it is wrong somewhere):

from django import forms
from catalog.models import DrgCode  
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.conf import settings #without it I get an error that settings not defined

class CalculatorForm(forms.Form):
    drg_choice = forms.ModelMultipleChoiceField(queryset=DrgCode.objects.all(), widget=FilteredSelectMultiple("Somethings", is_stacked=False), required=True)

    class Media:
        css = {
            'all': (os.path.join(settings.BASE_DIR, '/static/admin/css/widgets.css'),),
        }
        js = ('/admin/jsi18n',)

有关此部分的问题:


  1. 我对 django.conf 导入正确吗?由于我没有看到它以我发现的任何材料进口的
    答案:在我的测试中,我确定如果使用 settings.BASE_DIR 部分,则必须导入 django.conf 。在各种来源中,有两种编写 css 路径的方法,这种方法对我有用。

  2. 我需要创建 widgets.css 和相应的目录?还是
    django会自己找到它?由于我使用 django-admin
    startproject
    cmd创建了骨架网站后,没有生成此类文件或目录
    答案:否。由于django会找到它们本身,因此无需创建 widgets.css 或任何文件。

  3. 与前面的 jsi18n 部分相同的问题。还有这是什么?我
    假定其javascript文件,但由于某种原因没有扩展名。
    我也找不到它吗?我应该创建它吗?怎么做?
    还是可以从某个地方复制它? 部分答案:无需创建它。只需在 urls.py 中指向它即可。仍然不确定确切的文件类型(或文件的位置)

  1. Am I right about django.conf import? Since I did not see it imported in any material I found. Answer: during my test I determined that django.conf import is necessary if using settings.BASE_DIR part. In various sources there was two ways of writing css path, this one worked for me.
  2. Do I need to create widgets.css and corresponding directory? Or django will find it itself? Since there is no such file or directory generated after I created skeleton-website using django-admin startproject cmd? Answer: No. There is no need to create widgets.css or any of the files since django finds them itself.
  3. Same question as previous for jsi18n part. Also what is this? I assume its javascript file, but it has no extension for some reason. Also I cannot find it anywhere? Should I create it? How to do that? Or I can copy it from somewhere? Partial answer: no need to create it. Just point at it in urls.py. Still do not know exactly that kind of file it is (or where it is)

在修改<$ c $之后c> forms.py 我应该通过添加 url(r'^ jsi18n / $','来修改 urls.py django.views.i18n.javascript_catalog',name ='jsi18n')

After amending forms.py I should ammend urls.pyby adding url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', name='jsi18n')

所以 urls.py 现在看起来像这样:

So urls.py now look like this:

from django.urls import path
from . import views
from django.conf.urls import url 


urlpatterns = [
    path('', views.index, name='index'),
    'django.views.i18n.javascript_catalog',
    name='jsi18n'),
]

问题:


  1. 我在做它吗?我应该将其添加到 urlpatterns 下面吗? 答案:如果可以的话,可以使用这种方法。

  1. Am I doing it wright or should I just add it below urlpatterns? Answer: This method if fine.

现在我需要设置 HTML 模板文件以呈现表单(与其他情况一样)。为此的代码(名为 DrgCalculator.html 的文件):

Now I need to set HTML template file for form to render (like in any other case). Code for it (file named DrgCalculator.html):

{% extends "base_generic.html" %}
   <script type="text/javascript" src="{% url 'jsi18n' %}" > </script>

  {{ form.media }}

  <form enctype="multipart/form-data" method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit" class="save btn btn-default">Submit</button>
  </form>




  1. 这部分内容或多或少清晰。但是也许我应该修改
    的东西或知道吗? 答案:应该更改。将在下面编写完整的代码。

  1. This part seems more or less clear. But maybe I should amend something or know about? Answer: Should be changed. Will write full code below.

最后,我需要调整 views.py 设置此表单及其所有相关内容的发生位置。

Lastly I need to adjust views.py to set where this form and everything related with it happens.

根据我的理解,本部分中的代码或多或少与小部件没有直接关系,但是为了完成所有工作并制作示例,我将使用我倾斜/获取的代码在这篇(非常好的)django教程

From what I understand code in this part is more or less is not directly related with widget, but to complete everything and make working example I will use code I leaned/got in this (very good) django tutorial:

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse

from catalog.models import DrgCode
from catalog.forms import CalculatorForm

def DrgCalculator(request):
    if request.method == 'POST':
        form = CalculatorForm(request.POST)
        if form.is_valid():
            return render(request, 'DrgCalculator.html')
    context = {
        'form': form,
    }
    return render(request, 'DrgCalculator.html', context)

问题:

我将如何使用
FilteredSelectMultiple ?我想我应该像其他小部件一样清理
forms.py 中的数据。所以我应该在 forms.py 类CalculatorForm 中添加下面的嵌套函数
是吗? 答案:是的,应该像其他情况一样清除数据。函数正确。

  1. Any remarks on this part of the code? Answer: Missing else: form = DrgCalculator(). Will write amended code below.
  2. How I will access values which user choose using FilteredSelectMultiple? I imagine I should clean data in forms.py like with other widgets. So I should add nested function below to my class CalculatorForm in forms.py am I right? Answer: Yes, data should be cleaned like in other cases. Function is correct.

def clean_CalculatorForm(self):
drg_choice = self.cleaned_data ['drg_choice']
return drg_choice

清洗后得到的数据将是列表还是字典?我
对吗? 回答:不,从此小部件用户输入中以QuerySet的身份收到

Data I will get after cleaning will be list or dictionary? Am I right? Answer: No, from this widget user input received as QuerySet

这就是我的全部问题,很抱歉,我的话题太长了,我试图将其尽可能清楚。如果我需要澄清一些事情,请告诉我。我将尝试对其进行编辑和更新,以使其对以后将要阅读的人们友好。

That is all my questions, sorry for long thread, I tried to make it as clear as possible. If I need to clarify something, please let me know. I will try to edit and update this, to make it friendly for people who will read it in future.

EDIT1:回答了我的一些问题。

Answered some of my questions.

编辑2:回答了我其余的问题。

Answered rest of my questions.

推荐答案

经过几天的研究和测试我设法使 FilteredSelectMultiple 小部件在用户窗体的管理页面外工作。如所答应的那样,我将尝试将积累的知识汇总为某种指南,希望对以后像我这样的人有所帮助。请注意,我远非专业人士(只是业余爱好者,没有计算机工程背景),所以我的观察可能并不完全正确,或者我的观察方法不是最好的,但是它可能会帮助您取得正确的成绩

After spending few days of research and testing I managed to get FilteredSelectMultiple widget working outside admin page in user form. As promised in question, I will try to synthesize my accumulated knowledge into some sort of guide which I hope will help someone like me in the future. Please note that I am far from professional (just a hobbyist wi no computer engineering background to be precise) so my observations might be not exactly correct or the way I done it not the best one, but it might help you to get on the right track.

因此从 FilteredSelectMultiple 小部件 forms.py 必须通过以下方式进行修改:导入窗口小部件,为其创建字段(类似于常规窗口小部件),并添加嵌套的 Media 类。代码示例:

So to begin with FilteredSelectMultiple widget forms.py have to be amended by importing widget, creating field for it (similar like with regular widgets) and adding nested Media class. Code example:

from django.contrib.admin.widgets import FilteredSelectMultiple    

class DrgCalculator(forms.Form):
        drg_choise = forms.ModelMultipleChoiceField(queryset=DrgCode.objects.all(),
                                                          label="Something",
                                                          widget=FilteredSelectMultiple("Title", is_stacked=False),
                                                          required=True)

        class Media:
            css = {
                'all': ('/static/admin/css/widgets.css',),
            }
            js = ('/admin/jsi18n',)

        def clean_drg_choise(self):
            drg_choise = self.cleaned_data['drg_choise']
            return drg_choise

在测试和研究期间确定的 class Media 应该照原样复制,并且不需要更改,以使小部件正常工作。此类中提到的文件将由django本身找到,因此无需搜索和复制它们(就像我读过的某些材料所述)。

As I determined during my test and research class Media should be copied as written and require no changes for widget to work. Files mentioned in this class will be found by django itself so no need to search and copy them (like told in some of the material I read).

创建表单后 urls.py 应该修改。在测试过程中,我发现,在较新的Django版本(或至少我使用的一个版本)中, javascript_catalog 被重命名,并且提供的url不能为字符串。因此代码应如下所示:

After creating form urls.py should be amended. During testing I found out, that in newer django versions (or at lest one I used) javascript_catalog is renamed and url provided cannot be string. So code should look like this:

from django.urls import path
from . import views
from django.conf.urls import url
from django import views as django_views

urlpatterns = [
    url(r'^jsi18n/$', django_views.i18n.JavaScriptCatalog.as_view(), name='jsi18n'),
]

现在,对于 htlm 模板,我相信还有更多的方法可以这样做,所以我只提供示例:

Now for the htlm template I am sure that there is more ways of doing it so I just provide example:

{% extends "base_generic.html" %}

{% block content %}
<div id='frame'>
    <form action="" method="post">
        <div id='sk_body'>
            <fieldset>
            <legend>Fill required fields</legend>      
                <form>
                    {% csrf_token %}
                    <table>
                        {{ form.media }}
                        {{ form.as_table }}
                        <script type="text/javascript" src="{% url 'jsi18n' %}"></script>
                    </table>
                        <input type="submit" value="Count">
                </form>
            </fieldset>
        </div>
    </form>
</div>
{% endblock %}

要从此小部件中以<$相当标准的代码接收数据应该使用c $ c> views.py ,例如我使用的示例代码:

To receive data from this widget fairly standard code in views.py should be used, example code I used:

def DRG_calcualtor(request):
    if request.method == 'POST':
        form = DrgCalculator(request.POST)
        if form.is_valid():
            choosen_drg = form.cleaned_data['drg_choise'] #result as QuerySet
            choosen_drg_list = list([str(i) for i in choosen_drg]) #you can convert it to list or anything you need             

            return render(request, 'DRGcalculator_valid.html')

        context = {
            'form': form,
            }
        return render(request, 'DRGcalculator.html', context)

    else:
        form = DrgCalculator()
    context = {
        'form': form,
        }
    return render(request, 'DRGcalculator.html', context)

这篇关于需要有关FilteredSelectMultiple小部件的指导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆