Vahid
Vahid

Reputation: 407

Django needs to restart server for changing data in template

The goal is to make texts in static templates like "about us" page dynamic with a model so that it can be edited easily later on. My model is as below:

class SiteData(models.Model):
    data_set_name = models.CharField(
        max_length=200, blank=False, null=False, default="نام مجموعه داده"
    )
    main_page_english_info = models.TextField(
        verbose_name="مقدمه انگلیسی", blank=True, null=True
    )
    main_page_persian_info = models.TextField(
        verbose_name="مقدمه فارسی", blank=True, null=True
    )

my view is as below:

class HomePageView(ListView):
    model = SiteData
    template_name: str = "core/index.html"

    site_data = SiteData.objects.get(pk=1)
    context_vars = {
        "site_data": site_data,
    }

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        context.update(HomePageView.context_vars)
        return context

and my template:

<p class="mt-3 text-justified text-english fw-semibold nm-text-color"
style="direction: ltr; ">{{ site_data.main_page_english_info }}</p>
            
<p class="mt-3 text-justified nm-text-color">{{ site_data.main_page_persian_info }}</p>

My problem with this method is two main issues:

  1. This method works and if I change data from admin panel, it will be applyed, BUT ONLY if I restarted development server! (ctrl + c and py manage.py runserver). Where is my problem? How can I solve this issue?
  2. My model itself isn't so dynamic itself, and this is why I'm also trying another method which I have other problems in that, and I've asked another question here. Now, I'll appreciate an answer to either of these question!

Upvotes: 1

Views: 511

Answers (1)

DanielB
DanielB

Reputation: 2958

You are fetching the SiteData instance when the server starts, instead of during the request. Move the query into the get_context_data method, E.g.

class HomePageView(ListView):
    model = SiteData
    template_name: str = "core/index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["site_data"] = self.model.objects.get(pk=1)
        return context

Original answer follows:

By default, the cached loader is used (see the loaders section here), which avoids django needed to read and parse the template for every request.

I recommend leaving this enabled, and restarting as required. However, if you absolutely need this, you can change the configuration using the TEMPLATE variable in your settings file. You can see the available options in the official documentation

Upvotes: 1

Related Questions