简体   繁体   中英

Django: Passing Kwargs as form Values to generic CBV Form

I have a form in which the value of the first field can be determined by the URL. ie: example.com/value/form in which value is the appropriate response to the first field on the form.

How can I pass this value to the form on the page?

class VarietyCreate(CreateView):
    template_name = "generic_create.html"
    model = Variety
    form_class = VarietyForm
    pk_url_kwarg = "pk"
    initial = {"product_group" : pk_url_kwarg}

    def get_success_url(self):
        return reverse("purchases:Variety Index", kwargs={'pk': self.kwargs.get('pk')})

What I have does not seem to work.

From my URLs:

url(r'^commodities/view/(?P<pk>[^\/]+)/create/$', views.VarietyCreate.as_view(), name='Variety Create'),

Found the answer based on this post .

class VarietyCreate(CreateView):
    template_name = "generic_create.html"
    model = Variety
    form_class = VarietyForm

    def get_initial(self):
        return {"product_group" : self.kwargs.get('pk')}

    def get_success_url(self):
        return reverse("purchases:Variety Index", kwargs={'pk': self.kwargs.get('pk')})

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