art
art

Reputation: 1412

django - CreateView - How to show a particular option as selected in dropdown

I have model as shown below.

class ProductGroup(models.Model):
    name = models.CharField(max_length=30,null=False, blank=False)
    category=TreeForeignKey('category.Category', null=False,blank=False)

I have a CreateView as

class CreateProductGroup(CreateView):
    model = ProductGroup
    fields = ['name', 'category']

My url pattern for this view is

url(r'^create-group/(?P<pk>[0-9]+)/$', views.CreateProductGroup.as_view(), name='create_group'),

I'm passing the category_id through url from the category_detail.html page as

<a href="{%url 'create_group' object.id %}">Create product group</a>

Here's my form

<form method="post">
        {% csrf_token %}
        {% bootstrap_form form %}
        {% buttons %}
            <button type="submit" class="btn btn-primary">
                Submit
            </button>
            
        {% endbuttons %}
    </form>

Now, how do I show the category corresponding to the id in the url as selected in the form?

Upvotes: 5

Views: 1257

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You can define the get_initial() method to return a dictionary to prepopulate the form; in that method you can get the value from self.kwargs.

def get_initial(self):
    return {'category': self.kwargs['pk']}

Alternatively, if the category ID is always supplied in the URL you may not want the category field to be displayed on the form at all; in which case, exclude it from the list of fields, and override the form_valid method to set it on save.

def form_valid(self, form):
    form.instance.category_id = self.kwargs['pk']
    return super(CreateProductGroup, self).form_valid(form)

Upvotes: 8

Related Questions