Django ChoiceField [英] Django ChoiceField

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

问题描述

我正在尝试解决以下问题:



我有一个网页,只能看到主持人。
此页面上显示的字段(用户注册后):

用户名,名字+姓氏,电子邮件,状态,相关性等。



我需要使用这个字段显示存储在db中的所有用户的信息,但是有两个字段有选择,所以我想选择主持人可以选择另一个选项,点击更新按钮后,这个字段将被更新为所选用户。



我可以显示状态和相关性字段的所有选项,并且在从下拉列表中选择新选项后,db将被更新。

我想显示下拉列表,并且选择存储在db中的选项。
我已经尝试了很多选项,我在很多时间里搜索了很多时间,并在StackOverFlow中搜索了答案或正确的方向,但没有找到任何东西。



对不起,我的英文不好,提前感谢您的帮助!



以下是我的代码的一部分:



models.py

  class profile(models.Model):
user = models.OneToOneField(User)

status = models.IntegerField(choices =((1,_(不相关)),
(2,_(评论)),
(3,_(可能相关)),
(4,_(相关)),
5,_(Leading candidate)),
default = 1)

关联= models.IntegerField(choices =((1,_(未读)),
(2,_(Read))),
default = 1)

forms.py

  class CViewerForm(forms.Form):

status = form s.ChoiceField(label =,
initial ='',
widget = forms.Select(),
required = True)

关联=表单。 ChoiceField(widget = forms.Select(),
required = True)

views.py

  @group_required('Managers')
@render_to('reader / view .html'
def admins_view(request):
users_list = Profile.objects.select_related('user')。all()
users_dict = dict()

如果request.method和request.method =='POST':
form = CViewerForm(request.POST)

如果form.is_valid():
d = form.cleaned_data
#获取所有选定的选项
status_list = request.POST.getlist('status')
relevance_list = request.POST.getlist('relevance')
#获取所有用户名在页面
users_list = request.POST.getlist('username')

#从所有这些列表中创建dict
users_dict = zip([user_user中的用户],[状态为status in status_list],[rel for rel in relevant_list])
#运行dict并执行批量更新
for user_dict中的user_dict:
Profile.objects.filter(user__username = user_dict [0]) .update(status = user_dict [1],relevance = user_dict [2])

return HttpResponseRedirect(reverse('reader:admins_view'))

else:
form = CViewerForm()

return {'users_list':users_list,
'user':request.user,
'form':form}

模板:

  ; form class =form-horizo​​ntalaction =method =postname =update-formclass =well form-inlineid =view_form> 
{%csrf_token%}
{{form.non_field_errors}}
{%隐藏在form.hidden_​​fields%}
{{hidden}}
{%endfor %}

{%if user.is_staff%}
< div>
< table class =table table-stripe table-condensed>
< thead>
< tr>
< th> {%trans'用户名'%}< / th>
< th> {%trans'电子邮件'%}< / th>
< th> {%trans'状态'%}< / th>
< th> {%trans'Relevance'%}< / th>
< / tr>
< / thead>
< tbody>
{%user_list%}中的用户
< tr>
< td>< input type =textREADONLY name =usernamevalue ={{user.user.username}}>< / td>
< td> {{user.user.first_name}}< / td>
< td> {{user.user.last_name}}< / td>
< td> {{user.user.email}}< / td>
< td> {{user.get_status_display}}< / td>
< td> {{user.get_relevance_display}}< / td>
< / tr>
{%endfor%}
< / tbody>
< / table>
< / div>
{%endif%}
< br>
{%endif%}
< div class =form-actions>
< input type =hiddenname =_ cmd_personal>
< input type =submitclass =btn btn-infovalue ={%trans'更新'%}name =updateclass =default>
< / div>
< / form>






以下是一个解决方案:



forms.py(as @Liarez写道)



模板:

 < form class =form-horizo​​ntalaction =method =postname =update-formclass =well form-inlineid =view_form > 
{%csrf_token%}
{%if user.is_staff%}
{%if users_list%}
< div>
< table class =table table-stripe table-condensed>
< thead>
< tr>
< th> {%trans'用户名'%}< / th>
< th> {%trans'名字'%}< / th>
< th> {%trans'姓氏%}< / th>
< th> {%trans'电子邮件'%}< / th>
< th> {%trans'CV状态'%}< / th>
< th> {%trans'CV相关性'%}< / th>
< / tr>
< / thead>
< tbody>
{%user_list%}中的用户
< tr>
< td>< input type =textREADONLY name =usernamevalue ={{user.user.username}}>< / td>
< td> {{user.user.first_name}}< / td>
< td> {{user.user.last_name}}< / td>
< td> {{user.user.email}}< / td>
< td>
< select name =cv_status>
{%for key,status_choices%}中的状态
{%ifequal user.get_cv_status_display status%}
< option value ={{user.cv_status}}> {{user .get_cv_status_display}}< / option>
{%else%}
< option value ={{key}}> {{status}}< / option>
{%endifequal%}
{%endfor%}
< / select>
< / td>
< td>
< select name =cv_signal>
{%for key,signal_choices%}中的信号
{%ifequal user.get_cv_signal_display signal%}
< option value ={{user.cv_signal}}已选择> {{user .get_cv_signal_display}}< / option>
{%else%}
< option value ={{key}}> {{signal}}< / option>
{%endifequal%}
{%endfor%}
< / select>
< / td>
< / tr>
{%endfor%}
< / tbody>
< / table>
< / div>
{%endif%}
< br>
{%endif%}
< div class =form-actions>
< input type =submitclass =btn btn-infovalue ={%trans'更新'%}name =updateclass =default>
< / div>

解决方案

首先,我建议您@ ChrisHuang-Leaver建议您定义一个新文件,其中包含您需要的所有选项,如 choices.py

  STATUS_CHOICES =(
(1,_(不相关)),
(2,_ )
(3,_(可能相关)),
(4,_(相关)),
(5,_

RELEVANCE_CHOICES =(
(1,_(未读)),
(2,_(读))

现在,您需要在模型上导入它们,因此代码很容易理解(模型)。 py ):

  from myApp.choices import * 

class Profile(models。模型):
user = models.OneToOneField(User)
status = models.IntegerField(choices = STATUS_CHOICES,default = 1)
relevance = models.IntegerField(choices = RELEVANCE_CHOICES,default = 1 )

而您必须在 forms.py 中导入选项


$ b $来自myApp.choices import的



  

class CViewerForm(forms 。$)

status = forms.ChoiceField(choices = STATUS_CHOICES,label =,initial ='',widget = forms.Select(),required = form.ChoiceField(choices = RELEVANCE_CHOICES,required = True)

无论如何,您的模板有问题,因为您没有使用任何 {{form.field}} ,您生成一个表,但没有任何输入只有hidden_​​fields。



当用户是员工时,您应该生成与您可以管理的用户一样多的输入字段。我认为django形式不是你的情况的最佳解决方案。



我认为使用html表单会更好,所以您可以使用boucle生成尽可能多的输入: {%for user in users_list%} ,并生成与用户相关的ID的输入,您可以在视图中管理所有ID。


I'm trying to solve following issue:

I have a web page that can see only moderators. Fields displayed on this page (after user have registered):
Username, First name+Last name, Email, Status, Relevance, etc.

I need to display table with information of all users stored in db with this fields, but two of fields have choices, so I want to make option that moderators can choose another option and after clicking on "Update" button this fields will be updated for selected user.

I can to display all choices of "status" and "relevance" fields, and after I choose new options from dropdown db is updated.
I want to display dropdowns and option stored in db should be selected. I've tried a lot of options, I googled a lot of my time, and searched for answer or for right direction in StackOverFlow too, but didn't find anything.

Sorry for my bad english and thank you in advance for help!

Below is part of my code:

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User)

    status = models.IntegerField(choices=((1, _("Not relevant")),
                                        (2, _("Review")),
                                        (3, _("Maybe relevant")),
                                        (4, _("Relevant")),
                                        (5, _("Leading candidate"))),
                                default=1)

    relevance = models.IntegerField(choices=((1, _("Unread")),
                                        (2, _("Read"))),
                                default=1)

forms.py:

class CViewerForm(forms.Form):

    status = forms.ChoiceField(label="",
                                initial='',
                                widget=forms.Select(),
                                required=True)

    relevance = forms.ChoiceField(widget=forms.Select(),
                              required=True)

views.py:

@group_required('Managers')
@render_to('reader/view.html')
def admins_view(request):
    users_list = Profile.objects.select_related('user').all()
    users_dict = dict()

    if request.method and request.method == 'POST':
        form = CViewerForm(request.POST)

    if form.is_valid():
        d = form.cleaned_data
        # get all selected choices
        status_list = request.POST.getlist('status')
        relevance_list = request.POST.getlist('relevance')
        # get all usernames viewed on page
        users_list = request.POST.getlist('username')

        # create dict from all those lists
        users_dict = zip([user for user in users_list], [status for status in status_list], [rel for rel in relevance_list])
        # run through dict and do bulk update
        for user_dict in users_dict:
            Profile.objects.filter(user__username=user_dict[0]).update(status=user_dict[1], relevance=user_dict[2])

        return HttpResponseRedirect(reverse('reader:admins_view'))

else:
    form = CViewerForm()

return {'users_list': users_list,
        'user': request.user,
        'form': form}

template:

<form class="form-horizontal" action="" method="post" name="update-form" class="well form-inline" id="view_form">
            {% csrf_token %}
            {{ form.non_field_errors }}
            {% for hidden in form.hidden_fields %}
               {{ hidden }}
            {% endfor %}

            {% if user.is_staff %}
                    <div>
                        <table class="table table-striped table-condensed">
                            <thead>
                                <tr>
                                    <th>{% trans 'Username' %} </th>
                                    <th>{% trans 'E-mail' %} </th>
                                    <th>{% trans 'Status' %} </th>
                                    <th>{% trans 'Relevance' %} </th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for user in users_list %}
                                <tr>
                                    <td><input type="text" READONLY name="username" value="{{ user.user.username }}"></td>
                                    <td>{{ user.user.first_name }}</td>
                                    <td>{{ user.user.last_name }}</td>
                                    <td>{{ user.user.email }}</td>
                                    <td>{{ user.get_status_display }}</td>
                                    <td>{{ user.get_relevance_display }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% endif %}
                <br>
            {% endif %}
            <div class="form-actions">
                <input type="hidden" name="_cmd_personal">
                <input type="submit" class="btn btn-info" value="{% trans 'Update' %}" name="update" class="default">
            </div>
        </form>


Below is a solution:

forms.py (as @Liarez wrote).

template:

<form class="form-horizontal" action="" method="post" name="update-form" class="well form-inline" id="view_form">
{% csrf_token %}
{% if user.is_staff %}
    {% if users_list %}
        <div>
            <table class="table table-striped table-condensed">
                <thead>
                    <tr>
                        <th>{% trans 'Username' %} </th>
                        <th>{% trans 'First name' %} </th>
                        <th>{% trans 'Last name' %} </th>
                        <th>{% trans 'E-mail' %} </th>
                        <th>{% trans 'CV Status' %} </th>
                        <th>{% trans 'CV Relevance' %} </th>
                    </tr>
                </thead>
                <tbody>
                    {% for user in users_list %}
                    <tr>
                        <td><input type="text" READONLY name="username" value="{{ user.user.username }}"></td>
                        <td>{{ user.user.first_name }}</td>
                        <td>{{ user.user.last_name }}</td>
                        <td>{{ user.user.email }}</td>
                        <td>
                            <select name="cv_status">
                                {% for key, status in status_choices %}
                                    {% ifequal user.get_cv_status_display status %}
                                        <option value="{{ user.cv_status }}" selected>{{ user.get_cv_status_display }}</option>
                                    {% else %}
                                        <option value="{{ key }}">{{ status }}</option>
                                    {% endifequal %}
                                {% endfor %}
                            </select>
                        </td>
                        <td>
                             <select name="cv_signal">
                                {% for key, signal in signal_choices %}
                                    {% ifequal user.get_cv_signal_display signal %}
                                        <option value="{{ user.cv_signal }}" selected>{{ user.get_cv_signal_display }}</option>
                                    {% else %}
                                        <option value="{{ key }}">{{ signal }}</option>
                                    {% endifequal %}
                                {% endfor %}
                            </select>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    {% endif %}
    <br>
{% endif %}
<div class="form-actions">
    <input type="submit" class="btn btn-info" value="{% trans 'Update' %}" name="update" class="default">
</div>

解决方案

First I recommend you as @ChrisHuang-Leaver suggested to define a new file with all the choices you need it there, like choices.py:

STATUS_CHOICES = (
    (1, _("Not relevant")),
    (2, _("Review")),
    (3, _("Maybe relevant")),
    (4, _("Relevant")),
    (5, _("Leading candidate"))
)
RELEVANCE_CHOICES = (
    (1, _("Unread")),
    (2, _("Read"))
)

Now you need to import them on the models, so the code is easy to understand like this(models.py):

from myApp.choices import * 

class Profile(models.Model):
    user = models.OneToOneField(User)    
    status = models.IntegerField(choices=STATUS_CHOICES, default=1)   
    relevance = models.IntegerField(choices=RELEVANCE_CHOICES, default=1)

And you have to import the choices in the forms.py too:

forms.py:

from myApp.choices import * 

class CViewerForm(forms.Form):

    status = forms.ChoiceField(choices = STATUS_CHOICES, label="", initial='', widget=forms.Select(), required=True)
    relevance = forms.ChoiceField(choices = RELEVANCE_CHOICES, required=True)

Anyway you have an issue with your template, because you're not using any {{form.field}}, you generate a table but there is no inputs only hidden_fields.

When the user is staff you should generate as many input fields as users you can manage. I think django form is not the best solution for your situation.

I think it will be better for you to use html form, so you can generate as many inputs using the boucle: {% for user in users_list %} and you generate input with an ID related to the user, and you can manage all of them in the view.

这篇关于Django ChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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