MikeVelazco
MikeVelazco

Reputation: 905

Q: Django crispy forms - change behavior depending url

I don't know how to implement this with django crispy forms.

I have an interface with a URL like this:

myurl.com/movements/new

And I have a select in the form with the type of movement.

When there is not a type of movement explicitly assigned, just shows the select without any option selected.

unselected

When user access to form with an URL like myurl.com/movements/income/ I want this select to have by default the income option.

income

And so on with every possible option.

I know that I can use JavaScript for this, but I think that it would be better to have it on the back-end.

How can I achieve this on the back-end part?

Upvotes: 0

Views: 118

Answers (1)

Yannic Hamann
Yannic Hamann

Reputation: 5225

models.py:

class MyModel(models.Model):
    CHOICES = (
        ('Income', 'Income'),
        ('Option2', 'Option2'),
        ('Option3', 'Option3'),
    )
    choice = models.CharField(max_length=25, choices=CHOICES)

urls.py:

urlpatterns = [
    url(
        regex=r'^new/(?P<option>[\w.@+-]+)/$',  # feel free to adjust the regex
        view=views.NewCreateView.as_view(),
        name='new'
    ),
    url(
        regex=r'^new/$',
        view=views.NewCreateView.as_view(),
        name='new'
    )
]

views.py:

class NewCreateView(CreateView):
    model = MyModel
    fields = ['choice']

    def get_form_kwargs(self):
        form_kwargs = super().get_form_kwargs()
        if 'option' in self.kwargs:
            if any(self.kwargs['option'] in choice for choice in MyModel.CHOICES):
                form_kwargs['initial']['choice'] = self.kwargs['option']
        return form_kwargs

The initial selection of the drop-down list is only given if you visit the URL new/ with a valid option like new/Income. Of course, you can adjust the URL according to your needs.

You could also override get_initial instead of get_form_kwargs.

Upvotes: 1

Related Questions