Ad

How To Display Contents Based On Their Category On Button Click In Same Page In Django?

I am working on a portfolio project. where I have to categorize the projects based on their Categories. I have given buttons for each categories and I have to display each contents of individual categories on Button Clicks below them. Eg. I have 2 projects in Design category. When I click Design I should get these two projects below the button.

I tried filtering of contents and successfully displayed them in other page but unable to display them in the same page.

Here is my Code: Models.py

class PortfolioCategory(models.Model):
    projectCategory = models.CharField(max_length=200)
    projectSummary = models.CharField(max_length=300)
    projectLink = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = "categories"

    def __str__(self):
        return self.projectCategory


class Portfolio(models.Model):
    projectName = models.CharField(max_length=250)
    projectLink = models.CharField(max_length=50, default="")
    projectImage = models.ImageField(upload_to="img/Portfolio/")
    projectContent = models.TextField(default="")
    projectCategory = models.ForeignKey(
        PortfolioCategory, verbose_name="Category", on_delete=models.CASCADE)

    def __str__(self):
        return self.projectName

Views.Py

def projectLink(request, projectLink):
    category = [c.projectLink for c in PortfolioCategory.objects.all()]
    if projectLink in category:
        categoryItems = Portfolio.objects.filter(
            projectCategory__projectLink=projectLink)
        myProjects = categoryItems.all()
        return render(
            request,
            "main/home.html#projectLink",
            {
                "projects": myProjects,
                "navbar": navbar,
            }
        )
    projectContent = Portfolio.objects.get(projectLink=projectLink)
    return render(
        request,
        "main/projectItem.html",
        {
            "project": projectContent,
            "navbar": navbar,
        }
    )


def homepage(request):
    return render(
        request=request,
        template_name="main/home.html",
        context={
            "portfolios": Portfolio.objects.all,
            "categories": PortfolioCategory.objects.all,
            "navbar": navbar,
            "socialLinks": socialIcons,
            "skillset": skills,
        })

home.html

<ul class="nav nav-tabs justify-content-center">
            {% for cat in categories  %}

            <li><a data-toggle="tab" target="_blank" rel="nofollow noreferrer" href="#{{cat.projectLink}}">{{cat.projectCategory}}</a></li>

            {% endfor %}
        </ul>
        <div class="tab-content">
            {% for cat in categories %}
            <div id="{{cat.projectLink}}" class="tab-pane fadeIn">
                {{cat.projectCategory}}
                 //Projects Detail Here

            </div>
            {% endfor %}
        </div>

I have to show the cards of each Projects on button clicks.

Ad

Answer

If you want to retrieve data without refreshing the page you should use AJAX to call your view asynchronously.

You can use XMLHttpRequest or the preferably the fairly new fetch() which is based on Promises.

You can break the process into to these steps:

1)Create a destination in urls.py that will call a view responsible for retrieving categories from your database.

path('some-destination/', views.get_category, name="get_category")

2)Make an asynchronous call using javascript to your new URL

 function callFunc() {
    fetch('some-destination/').then(
        function(response) {
            if (response.status == 200) {
                //manipulate and format your data here
                //you may need to use `then()` again
            }
        }).catch(function(err) {
        console.log('Fetch Error', err);
    });
}

3)create a function in views.py that retrieves your object or data that you need. If required serialize it as JSON and return a response to your AJAX call

Now your button just needs to initiate your AJAX call

<input type="button" onclick="callFunc()" value="get categories">

If you are not familiar with Promises just use XMLHttpRequest or JQuery's AJAX

Ad
source: stackoverflow.com
Ad