4

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 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Works perfectly. Had to format a little form.instance.env = Env.objects.get(pk=self.kwargs['envid']) (since its a foriegn key for Env class)
To set a default value but still let the user decide, get_initial might be a good alternative.
here's the link for Django 4.6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.