formset并为每个外键输入文本 [英] formset and input text for each foreign key

查看:223
本文介绍了formset并为每个外键输入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 django formset 中,我试图用外键 >输入而不是选择

 类MinAttend(models.Model):
act = models.ForeignKey(Act)
country = models.ForeignKey(Country)
verbatim = models.ForeignKey(verbatim)
def __unicode __(self):
return u%s%self.verbatim
$ b $ class MinAttendForm(forms.ModelForm):
country = forms.ModelChoiceField(queryset = Country.objects .all(),empty_label =选择一个国家)
status = forms.ModelChoiceField(queryset = Status.objects.values_list('status',flat = True).distinct(),empty_label =选择一个状态)
verbatim = forms.CharField(max_length = 300)

类Meta:
模型= MinAttend
用于验证和订单的字段
fields =('country','status','verbatim')

ld,我有一个输入框,而不是一个选择,但是当我想更新一个formset,我有逐字id而不是相应的文本:


这里是我如何初始化表单:


$ < MinAttendForm
nb_extra_forms = 3
$ b $ def post(self,request,* args,** kwargs):
attendances = MinAttend.objects.filter(...)
#设置表格的数量到部长的数量+ 3额外的表格来填充,如果需要的话
MinAttendFormSet = modelformset_factory(self.model,form = self.form_class,extra = len(attendances),max_num = len(attendance )+ self.nb_extra_forms,can_delete = True)
formset = MinAttendFormSet(queryset = attendances)

我试过两件事:

而不是th最后一行我有以下代码:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $#
initials.append({verbatim:attendances [index] .verbatim.verbatim})
打印首字母缩写,首字母缩写
formset = MinAttendFormSet(queryset = attendances,initial = initials)

我重写了 init 形式的方法:

 #〜#verbatim text,而不是id 
def __init __(self,* args,** kwargs):
super(MinAttendForm,self).__ init __(* args,** kwargs)
instance = kwargs.get(instance ,None)
if instance!= None:
printinstance,instance.verbatim.verbatim
self.fields [verbatim]。initial = instance.verbatim.verbatim

这些方法都不起作用,我仍然得到数字而不是文本!奇怪的是,我确实在逐字字段中看到了文本,但是只有三种额外的形式。正常?

编辑 - 从Bernd Jerzyna评论



表格中:

  from django.forms.models import BaseModelFormSet 

class MinAttendFormSet(BaseModelFormSet):
def __init __(
super(MinAttendFormSet,self).__ init __(* args,** kwargs)
for self.forms中的表单:
#skip extra forms $($ args,** kwargs) b $ b如果不是form.empty_permitted:
form.fields ['verbatim']。initial = form.instance.verbatim
printverbatim MinAttendFormSet,form.instance.verbatim

在我的视图中:

<$ p $从表单中导入MinAttendForm,MinAttendFormSet
my_formset = modelformset_factory(self.model,form = self.form_class,formset = MinAttendFormSet)
formset = my_formset(request.POST,queryset =出勤)

当我做每个版本的文本打印巴蒂姆,我看到正确的文字显示。但是,我仍然看到我的网页形式的数字(主键ids);(。

有什么不对?



作为选择小部件,逐字显示与 __ unicode __ 结果,但是幕后的值是PK / verbatim-id,即 HTML < option> ; 标签有一个值和'label',当你把它改成一个文本输入部件时,期望你输入PK,所以为什么你看到数字。
$ b

对于解决方案,我不确定,你可以写一些代码来接受逐字文本,而不是pk / verbatim-id,但是这个问题是,如果文本django不会找到匹配,而且,如果超过1个逐字文本具有相同的文本,django将不知道要使用哪一个(除非您已经设置了 unique = true )。也可以将逐字文本设置为PK。

也许使用类似于 Django-Select2 会给你想要的用户界面吗?


In my django formset, I am trying to display a foreign key field with an input instead of a select:

class MinAttend(models.Model):
    act = models.ForeignKey(Act)
    country = models.ForeignKey(Country)
    verbatim = models.ForeignKey(Verbatim)
    def __unicode__(self):
        return u"%s" % self.verbatim

class MinAttendForm(forms.ModelForm):
    country=forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select a country")
    status=forms.ModelChoiceField(queryset=Status.objects.values_list('status', flat = True).distinct(), empty_label="Select a status")
    verbatim=forms.CharField(max_length=300)

    class Meta:
        model=MinAttend
        #fields used for the validation and order
        fields = ('country', 'status', 'verbatim')

For the verbatim field, I do have an input box instead of a select but when I want to update a formset, I have the verbatim id instead of its corresponding text:

Here is how I initialize the form:

class MinAttendUpdate(UpdateView):
    object=None
    model = MinAttend
    form_class=MinAttendForm
    nb_extra_forms=3

    def post(self, request, *args, **kwargs):
        attendances=MinAttend.objects.filter(...)
        #set the number of forms to the number of ministers + 3 extra form to fill if needed
        MinAttendFormSet = modelformset_factory(self.model, form=self.form_class, extra=len(attendances), max_num=len(attendances)+self.nb_extra_forms, can_delete=True)
        formset=MinAttendFormSet(queryset=attendances)

I have tried two things:

Instead of the last line I have the following code:

initials=[]
#display text of verbatim instead of id
for index in range(len(attendances)):
    initials.append({"verbatim": attendances[index].verbatim.verbatim})
print "initials", initials
formset=MinAttendFormSet(queryset=attendances, initial=initials)

I have overridden the init method of the form:

#~ #verbatim text instead of id for the verbatim field
def __init__(self, *args, **kwargs):
    super(MinAttendForm, self).__init__(*args, **kwargs)
    instance = kwargs.get("instance", None)
    if instance!=None:
        print "instance", instance.verbatim.verbatim
        self.fields["verbatim"].initial = instance.verbatim.verbatim

None of these methods works, I still get numbers instead of text! What is curious is that I do see text for the verbatim field but only for the three extra forms. Normal?

EDIT - from Bernd Jerzyna comment

In my form:

from django.forms.models import BaseModelFormSet

class MinAttendFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(MinAttendFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            #skip extra forms
            if not form.empty_permitted:
                form.fields['verbatim'].initial= form.instance.verbatim
                print "verbatim MinAttendFormSet", form.instance.verbatim

In my view:

from forms import MinAttendForm, MinAttendFormSet
my_formset = modelformset_factory(self.model, form=self.form_class, formset=MinAttendFormSet)
formset = my_formset(request.POST, queryset=attendances)

When I do a print of the text of each verbatim, I see the correct text displayed. However, I still see numbers (primary key ids) in the form of my web page ;(.

What's wrong?

解决方案

This is my understanding of it...

As a select widget, the verbatim is displayed with the __unicode__ results, but the value 'behind the scenes' is the PK/verbatim-id, ie the HTML <option> tag has a value and 'label'. When you change it to a text input widget, it is expecting you to enter the PK, hence why you are seeing the numbers.

For the solution, I am not sure. You could write some code to accept the verbatim-text, rather than the pk/verbatim-id. The problem with this though, is that if the text is not written exactly, django won't find a match. Also, if more than 1 verbatim has the same text, django wouldn't know which one to use (unless you have set unique=true on the model field for text). You could also set the verbatim-text as the PK.

Perhaps using something like Django-Select2 will give you the desired UI?

这篇关于formset并为每个外键输入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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