Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make fields optional #368

Closed
akrf opened this issue Jan 30, 2015 · 1 comment
Closed

How to make fields optional #368

akrf opened this issue Jan 30, 2015 · 1 comment
Labels

Comments

@akrf
Copy link

akrf commented Jan 30, 2015

I have a model with a optional many to many relationship to another model.

class Author(models.Model):
    name = models.Charfield(max_length=255, unique=True)
    ...

class Article(models.Model):
    name = models.Charfield(max_length=255, unique=True)
    authors = models.ManyToManyField(Author, blank=True, null=True)
    ...

I want to use django-autocomplete-light to allow auto-completion for authors on my article creation view, so I create a model form.

class ArticleForm(autocomplete_light.ModelForm):

    class Meta:
        model = Article
        fields = ['name', 'authors', ...]

That works great in my view, just as expected. The author field is optional, and auto suggestions work. But now I want to limit the authors that are suggested, so I create a new autocomplete and register it:

class AuthorAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['^name']

    def choices_for_request(self):
        # build the queryset and return it

And then alter the form to use it:

class ArticleForm(autocomplete_light.ModelForm):
    authors = autocomplete_light.ModelMultipleChoiceField('AuthorAutocomplete')

    class Meta:
        model = Article
        fields = ['name', 'authors', ...]

Now auto-completion works, the suggested authors are limited to the choices I want, but the authors field is required on the form. Where do I specify that the authors field is still optional?

@jpic
Copy link
Member

jpic commented Jan 31, 2015

On Fri, Jan 30, 2015 at 11:48 PM, akrf notifications@github.com wrote:

authors =
autocomplete_light.ModelMultipleChoiceField('AuthorAutocomplete')

required=False.

Here the most DRY option would be to have something like
ArticleForm.Meta.autocomplete_light_configuration = {'author': 'AuthorAutocomplete'}

Pull requests are welcome B0

http://yourlabs.org http://blog.yourlabs.org
Customer is king - Le client est roi - El cliente es rey.

@jpic jpic closed this as completed Apr 7, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants