willer2k
willer2k

Reputation: 546

How can I generate a multi-step process in Django without changing pages (w/out a new request)?

I have a model (Category) which references itself for its parent category. The categorty's roots can be found with a filter and aggregated into a select dropdown for example. But how would you generate another dropdown with the selected categories sub-category?

As far as I can tell, the solution would be to use Django REST api, but it seems like a bit of an overkill just to select a category.

Would anyone have any suggestions?

My model is:

class Category(models.Model):
    # PK
    cat_id = models.IntegerField(primary_key=True)

    # Foreign
    parent_category = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)

    # Column
    name = models.CharField(max_length=128) # the name of the category
    limit_message = models.CharField(max_length=255, null=True, blank=True)
    level = models.PositiveIntegerField() # 1 for root (major category) followed by 2, 3 ...
    is_leaf = models.BooleanField()
    is_enabled = models.BooleanField(default=True)

    def __str__(self):
        return self.name

Upvotes: 0

Views: 33

Answers (1)

Risul Islam
Risul Islam

Reputation: 806

You can use ajax to request a url for child categories using parent id. You'll need to write a view that returns child categories in json format.

Assuming your categories.py view has a function that returns child categories in json

return HttpResponse(simplejson.dumps(categories), content_type="application/json")

Use ajax to request data from front end.

$.ajax({
    url: request_url,
    success: function(data){
    $.each(data, function(id, text){
        $('select[name=sub-category]').append(
            $('<option></option>').val(id).html(text)
        );
    };
});

Upvotes: 1

Related Questions