简体   繁体   中英

Django ModelFormset name instead of ID in foreign key field

I'm having a problem with modelformset custom field so to speak. This is the code so far and it works fine:

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:

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:

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. 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. 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.

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? That is my recommendation to handle this situation. Here is the documentation on setting 'choices' in Django:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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