Django CreateView customise form default field based on url parameter

2.6k views Asked by At

file: Capacity/models.py

class Env(models.Model):
    name = models.CharField(max_length=50)
    def get_absolute_url(self):
            return reverse('index')

class Envhosts(models.Model):
    env =  models.ForeignKey(Env)
    hostname = models.CharField(max_length=50)
    count = models.IntegerField()

    class Meta:
        unique_together = ("env","hostname")

    def get_absolute_url(self):
        return reverse('index')

file: Capacity/views.py

 class EnvhostsCreate(CreateView):
    model = Capacity.models.Envhosts
    fields=['env','hostname','count']
    template_name_suffix = '_create_form'

file Capacity/urls.py:

urlpatterns = patterns(........ url(r'^createhosts/(?P<envid>\d+)/$',EnvhostsCreate.as_view(),name='envhosts_create'))

So now, when i open this form: /Capacity/createhosts/3/ (where 3 is my env id) It shows an option of env objects as a drop down list based on the number of object of Env. But i want it to take the env on its own based on the env id ('3' in this case)

I know i have to override some method in class EnvhostsCreate(CreateView). But i m unable to figure out which method and how to take the env based on the part after /createhosts/

1

There are 1 answers

3
Daniel Roseman On BEST ANSWER

You can use the pattern described in the documentation for adding request.user - it's the same principle. Remove env from the fields list, then define form_valid():

class EnvhostsCreate(CreateView):
    model = Capacity.models.Envhosts
    fields = ['hostname', 'count']
    template_name_suffix = '_create_form'

    def form_valid(self, form):
        form.instance.env = Envhosts.objects.get(pk=self.kwargs['envid'])
        return super(EnvhostsCreate, self).form_valid(form)