[Answered ]-Django: Accessing URL variables in Class Based Views and Forms

2πŸ‘

βœ…

To access the data passed to the view, use self.args and self.kwargs

from accounts.forms import *
from accounts.models import *

class CreateSubscription(CreateView):
    model = Subscription
    form_class = CreateSubscriptionForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.site = Site.objects.get(domain=self.kwargs['domain'])
        return super(CreateSubscription, self).form_valid(form)

To restrict the dropdown content, you need to set the queryset for those fields. Very basically, something along these lines:

class CreateSubscriptionForm(forms.ModelForm):
    plan = forms.ModelChoiceField(
        queryset=SubscriptionPlan.objects.filter(xxx)
    )

    ...

    class Meta:
        model = Subscription
        exclude = ('user', 'site', )

This can also be done inside the view so that you have access to the domain.

class CreateSubscription(CreateView):
    model = Subscription
    form_class = CreateSubscriptionForm

    def get_form(self, form_class):
        """
        Returns an instance of the form to be used in this view.
        """
        form = super(CreateSubscription, self).get_form(form_class)
        form.fields['plan'].queryset = SubscriptionPlan.objects.filter(site__domain=self.kwargs['domain'])
        return form

    ...

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.site = Site.objects.get(domain=self.kwargs['domain'])
        return super(CreateSubscription, self).form_valid(form)
πŸ‘€Ngenator

Leave a comment