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
仅当您使用有效选项(如 new/Income)访问 URL new/ 时,才会给出下拉列表的初始选择。当然,您可以根据需要调整网址。
您也可以覆盖 get_initial 而不是 get_form_kwargs。