简体   繁体   English

如何在没有 model 的情况下使用 forms.py 创建 Django 下拉表单?

[英]How to create a Django dropdown form using forms.py without a model?

I need to create a simple presentation filter for a Django webpage.我需要为 Django 网页创建一个简单的演示过滤器。 Since it's discarded without need for storage, I do not need to use Model overhead.由于它被丢弃而不需要存储,我不需要使用 Model 开销。

Here is my relevant views.py code:这是我的相关views.py代码:

@login_required()
def cards(request):
    # form = CountryForm()
    f_name = STAT_FILES / 'csv/segment_summary_quart.csv'
    # pathname = os.path.abspath(os.path.dirname(__file__))
    df = pd.read_csv(f_name, index_col=None)

    pl_name = STAT_FILES / 'pickles/lbounds'
    pu_name = STAT_FILES / 'pickles/ubounds'
    lbounds = pickle.load(open(pl_name, "rb"))
    ubounds = pickle.load(open(pu_name, "rb"))

    filter_name = []
    i = 0
    max_i = len(ubounds)
    while i < max_i:
        filter_name.append(f'Personal best trophy range: {str(int(lbounds[i])).rjust(4," ")}-{str(int(ubounds[i])).rjust(4," ")}')
        i += 1

    sort_name = []
    sort_name.append("Alphabetic Order")
    sort_name.append("Most Popular")
    sort_name.append("Least Popular")
    sort_name.append("Highest Win Rate")
    sort_name.append("Lowest Win Rate")

    form = cardStatsForm(filter_name, sort_name)

Given that my values may change dynamically, I am trying to establish the cardStatsForm() object without initially knowing the values that will occur when publishing the page to the end user.鉴于我的值可能会动态变化,我正在尝试建立 cardStatsForm() object,但最初并不知道将页面发布给最终用户时会出现的值。 The following code resides within forms.py:以下代码位于 forms.py 中:

from django import forms


class cardStatsForm(forms.Form):
    def __init__(self, filter_opts, sortOrder, *args, **kwargs):
        super(cardStatsForm, self).__init__(*args, **kwargs)
        self.fields['filts'].choices = filter_opts
        self.fields['sorts'].choices = sortOrder

    filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True)
    sorts = forms.Select(choices=())

Unfortunately I haven't had to worry about the html side yet since I keep getting the following error with respect to my form class:不幸的是,我不必担心 html 方面,因为我一直收到有关我的表格 class 的以下错误:

KeyError at /clashstats/cards/
'sorts'
Request Method: GET
Request URL:    http://127.0.0.1:8000/clashstats/cards/
Django Version: 4.0
Exception Type: KeyError
Exception Value:    
'sorts'
Exception Location: /Users/cooneycw/PycharmProjects/The6ix/clashstats/forms.py, line 8, in __init__
Python Executable:  /Users/cooneycw/miniforge3/envs/The6ix/bin/python

I am more familiar with the flask framework and see that Django relies more heavily on objects which I am less familiar with.我更熟悉 flask 框架,并看到 Django 更多地依赖于我不太熟悉的对象。 What am i doing incorrectly here?我在这里做错了什么?

The solution recommend by AMG above enabled me to move past this error.上面 AMG 推荐的解决方案使我能够克服这个错误。 The next error related to the expectation for tuples for the choice listings.下一个错误与选项列表的元组期望相关。 The following code modified to send zipped tuples for the list items now completes successfully:为发送列表项的压缩元组而修改的以下代码现在已成功完成:

forms.py forms.py

from django import forms


class cardStatsForm(forms.Form):
    def __init__(self, filterList, sortList, *args, **kwargs):
        super(cardStatsForm, self).__init__(*args, **kwargs)
        self.filts = []
        self.sorts = []
        self.fields['filts'].choices = filterList
        self.fields['sorts'].choices = sortList

    filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True)
    sorts = forms.ChoiceField(choices=())

views.py视图.py

@login_required()
def cards(request):
    # form = CountryForm()
    f_name = STAT_FILES / 'csv/segment_summary_quart.csv'
    # pathname = os.path.abspath(os.path.dirname(__file__))
    df = pd.read_csv(f_name, index_col=None)

    pl_name = STAT_FILES / 'pickles/lbounds'
    pu_name = STAT_FILES / 'pickles/ubounds'
    lbounds = pickle.load(open(pl_name, "rb"))
    ubounds = pickle.load(open(pu_name, "rb"))

    filter_name = []
    i = 0
    max_i = len(ubounds)
    while i < max_i:
        filter_name.append(f'Personal best trophy range: {str(int(lbounds[i])).rjust(4," ")}-{str(int(ubounds[i])).rjust(4," ")}')
        i += 1
    filter_id = range(len(filter_name))
    filter_list = list(zip(filter_id, filter_name))

    sort_name = []
    sort_name.append("Alphabetic Order")
    sort_name.append("Most Popular")
    sort_name.append("Least Popular")
    sort_name.append("Highest Win Rate")
    sort_name.append("Lowest Win Rate")

    sort_id = range(len(sort_name))
    sort_list = list(zip(sort_id, sort_name))

    form = cardStatsForm(filter_list, sort_list)

My thanks to https://stackoverflow.com/users/4872140/amg for his help to resolve this issue.感谢https://stackoverflow.com/users/4872140/amg帮助解决了这个问题。

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

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