简体   繁体   English

Django ModelFormset名称而不是外键字段中的ID

[英]Django ModelFormset name instead of ID in foreign key field

I'm having a problem with modelformset custom field so to speak. 可以这么说,我对modelformset自定义字段有疑问。 This is the code so far and it works fine: 到目前为止,这是代码,它可以正常工作:

models.py: models.py:

class Workplace(models.Model):
    user = models.ForeignKey(User)
    description = models.TextField(blank=True, null=True)
    organization = models.ForeignKey(Organization)
    position = models.CharField(max_length=250, null=True)
    start = models.DateTimeField(null=True, blank=True)
    end = models.DateTimeField(null=True, blank=True)
    place = models.ForeignKey(Place, null=True, blank=True)
    deleted = models.BooleanField(default=False)

forms.py: forms.py:

class UserWorkplaceForm(forms.ModelForm):
    class Meta:
        model = Workplace
        labels = {
            'deleted': 'Delete this position'
        }

    def __init__(self, *args, **kwargs):
        super(UserWorkplaceForm, self).__init__(*args, **kwargs)
        self.fields['position'].required = True
        self.fields['organization'].required = True
        self.fields['start'].required = True

views.py: views.py:

def settings_workplace(request):
    workplace_formset = modelformset_factory(Workplace,
                                         form=UserWorkplaceForm,
                                         fields=('user', 'position', 'organization', 'start', 'end', 'deleted'),
                                         widgets={'user': forms.HiddenInput(),
                                                  'start': forms.DateInput(attrs={'class': 'workplace-date'}),
                                                  'end': forms.DateInput(attrs={'class': 'workplace-date'}),
                                                  'deleted': forms.CheckboxInput(),
                                                  'organization': forms.TextInput()
                                                  },
                                         extra=0)
    if request.method == "POST":
        formset = workplace_formset(request.POST)
        if formset.is_valid():
            formset.save()
            formset = workplace_formset(queryset=request.user.get_profile().workplace.filter(deleted=False))
    else:
        formset = workplace_formset(queryset=request.user.get_profile().workplace.filter(deleted=False))

    context = {
        'formset': formset
    }

    return render_to_response('accounts/settings_workplaces.html', context, RequestContext(request))

The 'organization' field is rendered as a Select HTML element. “组织”字段呈现为Select HTML元素。 I can't have that because there are thousands of organizations in the database. 我不能拥有它,因为数据库中有成千上万的组织。 What I'd like to do is display the Organization as a text field. 我想做的是将“组织”显示为文本字段。 That's what I did in the widgets part. 这就是我在小部件部分所做的。 However, that gives me the ID of the field, normally, not the name. 但是,这给了我该字段的ID,通常不是名称。 Is there a way for me to get both? 有办法让我两者兼得吗? I need the name for a nicer display and I need the ID in case editing happens (on a different field) because that field is required. 我需要一个更好的显示名称,并且需要ID(以防在其他字段上进行编辑),因为该字段是必需的。

Any ideas? 有任何想法吗?

Can you make it a ChoiceField where the 1st value is the ID of Organization, and the 2nd value is the Human Readable name of the Organization? 您能否将其第一个值为组织ID,第二个值为组织的人类可读名称作为ChoiceField That is my recommendation to handle this situation. 这是我处理这种情况的建议。 Here is the documentation on setting 'choices' in Django: 这是在Django中设置“选择”的文档:

https://docs.djangoproject.com/en/1.7/ref/forms/fields/#choicefield https://docs.djangoproject.com/zh-CN/1.7/ref/forms/fields/#choicefield

https://docs.djangoproject.com/en/1.7/ref/models/fields/#choices https://docs.djangoproject.com/zh-CN/1.7/ref/models/fields/#choices

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

相关问题 Django 返回字符串字段而不是外键上的 ID - Django Return String Field Instead of ID on Foreign Key Django ModelForm显示model外键字段代替object id - Django ModelForm display model field of foreign key instead object id 如何在 django 中获取字段名称而不是外部 ID - How to get field name instead of foreign id in django 如何使外键在django中接受字段值而不是其ID? - How to make foreign key accept field value instead of its id in django? 如何显示字段文本而不是Django中通过外键连接的模型的ID? - How to display field text instead of the ID for a model connected by a foreign key in Django? Django - 在 Django 模板中为 if 语句获取外键字段名称 - Django - get foreign key field name in django template for if statement 外部字段如何显示名称而不是其 id? - How can the foreign field shows the name instead of its id? Django管理表单,外键中的字段而不是对象 - Django admin form, field instead of object in foreign key 如何在 Django Rest Framework 中显示外键的字段值而不是 id 确保所有字段都像以前一样在 DRF HTML 表单上显示 - How to display field value instead of id for foreign key in Django Rest Framework ensuring all fields being displayed as before on DRF HTML form django-rest-framework- 接受提交的外键字段的 id - django-rest-framework- accepting id for submitted foreign key field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM