开发者

Customize inline_formset field display of foreign key

I have a model called Access that links to two other models.

class Access (models.Model):
    portfolio_id = models.ForeignKey(Portfolio)
    user_id = models.ForeignKey(User)
    title = models.CharField(max_length=30, null=True, blank=True)
    access_rights = models.PositiveIntegerField(choices=ACCESS_CHOICES)

I have created this 开发者_StackOverflowform.

class UserAccessForm(forms.ModelForm):
    class Meta:
    model = Access

I have this in the view.

AccessFormSet = inlineformset_factory(Portfolio,
                                      Access,
                                      form=UserAccessForm,
                                      extra=1,
                                      can_delete=False)
cAccessFormSet = AccessFormSet(instance=cPorfolio)

The issue is in the web page, user_id displays as a choicefield giving me a list of all my users (i.e. "jane15", "tom54"). I want it to be a text field that someone has to type in the username. When I try to customize it as below, it displays "user ids" instead of the "username" (i.e. "1", "2").

class UserAccessForm(forms.ModelForm):
    user_id = forms.ChoiceField(required=True, widget=forms.TextInput)
    class Meta:
        model = Access

How do I get the formset to display and accept usernames (i.e. "jane15") as a textfield instead of as a choicefield?


Well, if you wanted to type in usernames, a choice field is not the way to go.

Use a CharField which is a <input type='text'> and override the clean_FOO method to validate the input into a user instance or raise an error message.

class UserAccessForm(forms.ModelForm):
    user_id = forms.CharField()

    class Meta:
        model = Access

    def clean_user_id(self):
        data = self.cleaned_data.get('user_id')
        try:
            user = User.objects.get(username=data)
        except User.DoesNotExist:
            raise forms.ValidationError("No user exists by that username")
        return user

Pass that into your formset and you're done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜