Django: 20 html files: 20 TemplateViews and 20 URL patterns needed?












6















I have 20 Django simple "foo.html" template files.



Do I need 20 TemplateViews and 20 entries in url_patterns or is there a simpler solution?










share|improve this question





























    6















    I have 20 Django simple "foo.html" template files.



    Do I need 20 TemplateViews and 20 entries in url_patterns or is there a simpler solution?










    share|improve this question



























      6












      6








      6








      I have 20 Django simple "foo.html" template files.



      Do I need 20 TemplateViews and 20 entries in url_patterns or is there a simpler solution?










      share|improve this question
















      I have 20 Django simple "foo.html" template files.



      Do I need 20 TemplateViews and 20 entries in url_patterns or is there a simpler solution?







      django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 7 '18 at 13:32









      Alasdair

      181k26307309




      181k26307309










      asked Nov 7 '18 at 11:51









      guettliguettli

      3,42422132273




      3,42422132273
























          4 Answers
          4






          active

          oldest

          votes


















          11














          Using Django 2.1 and class-based views, your urls.py should be like this:



          from django.urls import path

          from your_app import views

          app_name = 'your_app'

          urlpatterns = [
          path('foo/<str:name>/', views.Foo.as_view(), name='foo'),
          ]


          And your views.py like this:



          from django.views import generic


          class Foo(generic.TemplateView):

          def get_template_names(self)
          name = self.kwargs.get('name')
          # compute the template you want, for the example, I just take the name
          template_name = f'your_app/{name}.html'
          return [template_name]


          And that's all ;)






          share|improve this answer
























          • This is a really nice solution with CBVs. A small improvement could be to ensure that the template really exists; a static list of allowed template names could be used or some kind of error catching (except TemplateDoesNotExist:) could be added somewhere in the view.

            – Ralf
            Nov 13 '18 at 21:54











          • @Ralf It is exactly the purpose of the comment "compute the template you want[...]" so... yeah, definitely ;)

            – mistiru
            Nov 13 '18 at 22:32





















          8





          +50









          You can have a path like path('pages/<str:page>, views.pages)



          And then in the view do something similar to:



          from django.template.loader import get_template
          from django.template import TemplateDoesNotExist

          def pages(request, page):
          template_name = f'your-app/{page}.html'
          try:
          get_template(template_name)
          return render(request, template_name)
          except TemplateDoesNotExist:
          # returns 404





          share|improve this answer


























          • Is this still the way to go? I thought ClassBasedViews are used today.

            – guettli
            Nov 7 '18 at 13:56






          • 1





            You can do it also with a class based view. But I think don't exist a generic class to do what you want to achieve. You will end up using simple view with a get method and the same body. So, in this case, is indifferent whatever you want to use.

            – grouchoboy
            Nov 7 '18 at 14:04













          • It does exist: extend TemplateView, then set template_name accordingly. However I think you then need to do the logic within get_context_data() which you overide.

            – v25
            Nov 7 '18 at 15:58








          • 1





            @V25 I think the problem with TemplateView is that it expects template_name to be a str and in this case, it should be evaluated based on the request param. So, at the end it would be more difficult and less clean to do the required modifications to leave working it, than use a simple View

            – grouchoboy
            Nov 7 '18 at 16:13








          • 2





            @guettli: There's no reason to prefer a class based view when you can write a function view that is concise and simple like this. It is possible (but pointless) to rewrite this as a class based view, by subclassing View and turning this function into a get method.

            – Håken Lid
            Nov 10 '18 at 15:19





















          0














          A simpler solution with django 2.x.



          Since you sound newer to django, this solution should be much easier. There's no reason to use f strings and try/except blocks with simple things. And I know when I started, class based views made no sense because there was no control flow.



          urls.py



          from django.urls import path
          from . import views

          app_name = 'article_app'

          urlpatterns = [
          path('', views.article_list, name='article_list'),
          path('new/', views.article_new, name='article_new'),
          path('<int:art_pk>/', views.article_detail, name='article_detail'),
          path('<int:art_pk>/update/', views.article_update, name='article_update'),
          path('<int:art_pk>/delete/', views.article_delete, name='article_delete'),
          # and so on....
          ]


          views.py



          from django.shortcuts import render
          from .models import Article

          def article_detail(request, art_pk):
          article = Article.objects.get(pk=art_pk)
          return render(request, 'articles_app/article_detail.html', {'article': article})


          template for article_detail.html



          {% block maincontent %}

          <div class="article">
          <h2><u>{{ article.title }}</u></h2>
          <h3>By: {{ article.author }} --- Posted / Updated on: {{ article.date }}</h3>
          <p>{{ article.body }}</p>
          <p><a href="{% url 'article_app:article_update' article.pk %}">Update</a> | <a href="{% url 'article_app:article_delete' article.pk %}">Delete</a></p>
          <p><a href="{% url 'article_app:article_list' %}">Back to all articles</a></p>
          </div>

          {% endblock maincontent %}








          If you had something more complicated:



          Lets say it's something that requires a few if/else statements to describe a Food model. Example:



          models.py



          class Food(models.Model):
          FLAVOR_CHOICES = (
          ('tasty', 'Very yummy'),
          ('disgusting', 'Nasty AF bro!'),
          ('super_sweet', 'For little kids'),
          ('bitter', 'Sure to grow hair on you balls!'),
          )
          food_choice = models.CharField(max_length=30, choices=FLAVOR_CHOICES, default='super_sweet')
          # and any other attribute for a Food


          urls.py



          app_name = 'food_app'

          urlpatterns = [
          # ....
          path('<int:food_id>/', views.show_food, name='show_food'),
          ]


          views.py



          def show_food(request, food_id):
          food = Food.objects.get(id=food_id)
          if food.food_choice == 'tasty':
          return render(request, 'food_app/food_stats.html', {'tasty': 'Everyone likes tasty things'})
          elif food.food_choice == 'bitter':
          return render(request, 'food_app/food_stats.html', {'bitter': 'Girls do not want to have balls. Sure way to end the gene pool.'})
          # .... and so on with other choices
          else:
          return render(request, 'food_app/food_stats.html')


          Then your food_stats.html template would look something like this



          Note that this should be used instead of creating separate pages for 'bitter.html', 'tasty.html', 'super_sweet.html', etc.



          {% block maincontent %}

          <h1>Your choice of food:</h1>

          {% if tasty %}
          <p>{{ tasty.food_choice }}</p> {# this attribute would show the 2nd value for 'tasty' in the tuple of FLAVOR_CHOICES - 'Very yummy' #}
          <p>{{ tasty }}</p> {# The value that shows here is the key I set in the view #}

          {% elif disgusting %}
          <p>{{ disgusting.food_choice }}</p>
          <p>{{ disgusting }}</p>

          {% elif super_sweet %}
          <p>{{ super_sweet.food_choice }}</p>
          <p>{{ super_sweet }}</p>

          {% elif bitter %}
          <p>{{ bitter.food_choice }}</p>
          <p>{{ bitter }}</p>

          {% else %}
          <p>No foods bro. You're lame.</p>

          {% endif %}

          {% endblock maincontent %}





          share|improve this answer


























          • Your answer starts with "a simpler solution". That's a good start. I see that the answer is very long. For me it is too long.

            – guettli
            Nov 16 '18 at 11:28






          • 1





            I was showing everything that's needed. Since you didn' seem to understand, I thought I'd teach you how it all works together. And if you understood everything but the templates, then just read the templates.

            – PwnSauceDesigns
            Nov 17 '18 at 14:44





















          0














          from django.conf.urls import url
          from .import views



          urlpatterns = [
          # url(r'^/$', views.function_name, name="Page")



          url(r'^$', views.home, name="Home Page"),


          ]



          use this patterns match to show your .html pages






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53188920%2fdjango-20-html-files-20-templateviews-and-20-url-patterns-needed%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            11














            Using Django 2.1 and class-based views, your urls.py should be like this:



            from django.urls import path

            from your_app import views

            app_name = 'your_app'

            urlpatterns = [
            path('foo/<str:name>/', views.Foo.as_view(), name='foo'),
            ]


            And your views.py like this:



            from django.views import generic


            class Foo(generic.TemplateView):

            def get_template_names(self)
            name = self.kwargs.get('name')
            # compute the template you want, for the example, I just take the name
            template_name = f'your_app/{name}.html'
            return [template_name]


            And that's all ;)






            share|improve this answer
























            • This is a really nice solution with CBVs. A small improvement could be to ensure that the template really exists; a static list of allowed template names could be used or some kind of error catching (except TemplateDoesNotExist:) could be added somewhere in the view.

              – Ralf
              Nov 13 '18 at 21:54











            • @Ralf It is exactly the purpose of the comment "compute the template you want[...]" so... yeah, definitely ;)

              – mistiru
              Nov 13 '18 at 22:32


















            11














            Using Django 2.1 and class-based views, your urls.py should be like this:



            from django.urls import path

            from your_app import views

            app_name = 'your_app'

            urlpatterns = [
            path('foo/<str:name>/', views.Foo.as_view(), name='foo'),
            ]


            And your views.py like this:



            from django.views import generic


            class Foo(generic.TemplateView):

            def get_template_names(self)
            name = self.kwargs.get('name')
            # compute the template you want, for the example, I just take the name
            template_name = f'your_app/{name}.html'
            return [template_name]


            And that's all ;)






            share|improve this answer
























            • This is a really nice solution with CBVs. A small improvement could be to ensure that the template really exists; a static list of allowed template names could be used or some kind of error catching (except TemplateDoesNotExist:) could be added somewhere in the view.

              – Ralf
              Nov 13 '18 at 21:54











            • @Ralf It is exactly the purpose of the comment "compute the template you want[...]" so... yeah, definitely ;)

              – mistiru
              Nov 13 '18 at 22:32
















            11












            11








            11







            Using Django 2.1 and class-based views, your urls.py should be like this:



            from django.urls import path

            from your_app import views

            app_name = 'your_app'

            urlpatterns = [
            path('foo/<str:name>/', views.Foo.as_view(), name='foo'),
            ]


            And your views.py like this:



            from django.views import generic


            class Foo(generic.TemplateView):

            def get_template_names(self)
            name = self.kwargs.get('name')
            # compute the template you want, for the example, I just take the name
            template_name = f'your_app/{name}.html'
            return [template_name]


            And that's all ;)






            share|improve this answer













            Using Django 2.1 and class-based views, your urls.py should be like this:



            from django.urls import path

            from your_app import views

            app_name = 'your_app'

            urlpatterns = [
            path('foo/<str:name>/', views.Foo.as_view(), name='foo'),
            ]


            And your views.py like this:



            from django.views import generic


            class Foo(generic.TemplateView):

            def get_template_names(self)
            name = self.kwargs.get('name')
            # compute the template you want, for the example, I just take the name
            template_name = f'your_app/{name}.html'
            return [template_name]


            And that's all ;)







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 '18 at 14:09









            mistirumistiru

            420112




            420112













            • This is a really nice solution with CBVs. A small improvement could be to ensure that the template really exists; a static list of allowed template names could be used or some kind of error catching (except TemplateDoesNotExist:) could be added somewhere in the view.

              – Ralf
              Nov 13 '18 at 21:54











            • @Ralf It is exactly the purpose of the comment "compute the template you want[...]" so... yeah, definitely ;)

              – mistiru
              Nov 13 '18 at 22:32





















            • This is a really nice solution with CBVs. A small improvement could be to ensure that the template really exists; a static list of allowed template names could be used or some kind of error catching (except TemplateDoesNotExist:) could be added somewhere in the view.

              – Ralf
              Nov 13 '18 at 21:54











            • @Ralf It is exactly the purpose of the comment "compute the template you want[...]" so... yeah, definitely ;)

              – mistiru
              Nov 13 '18 at 22:32



















            This is a really nice solution with CBVs. A small improvement could be to ensure that the template really exists; a static list of allowed template names could be used or some kind of error catching (except TemplateDoesNotExist:) could be added somewhere in the view.

            – Ralf
            Nov 13 '18 at 21:54





            This is a really nice solution with CBVs. A small improvement could be to ensure that the template really exists; a static list of allowed template names could be used or some kind of error catching (except TemplateDoesNotExist:) could be added somewhere in the view.

            – Ralf
            Nov 13 '18 at 21:54













            @Ralf It is exactly the purpose of the comment "compute the template you want[...]" so... yeah, definitely ;)

            – mistiru
            Nov 13 '18 at 22:32







            @Ralf It is exactly the purpose of the comment "compute the template you want[...]" so... yeah, definitely ;)

            – mistiru
            Nov 13 '18 at 22:32















            8





            +50









            You can have a path like path('pages/<str:page>, views.pages)



            And then in the view do something similar to:



            from django.template.loader import get_template
            from django.template import TemplateDoesNotExist

            def pages(request, page):
            template_name = f'your-app/{page}.html'
            try:
            get_template(template_name)
            return render(request, template_name)
            except TemplateDoesNotExist:
            # returns 404





            share|improve this answer


























            • Is this still the way to go? I thought ClassBasedViews are used today.

              – guettli
              Nov 7 '18 at 13:56






            • 1





              You can do it also with a class based view. But I think don't exist a generic class to do what you want to achieve. You will end up using simple view with a get method and the same body. So, in this case, is indifferent whatever you want to use.

              – grouchoboy
              Nov 7 '18 at 14:04













            • It does exist: extend TemplateView, then set template_name accordingly. However I think you then need to do the logic within get_context_data() which you overide.

              – v25
              Nov 7 '18 at 15:58








            • 1





              @V25 I think the problem with TemplateView is that it expects template_name to be a str and in this case, it should be evaluated based on the request param. So, at the end it would be more difficult and less clean to do the required modifications to leave working it, than use a simple View

              – grouchoboy
              Nov 7 '18 at 16:13








            • 2





              @guettli: There's no reason to prefer a class based view when you can write a function view that is concise and simple like this. It is possible (but pointless) to rewrite this as a class based view, by subclassing View and turning this function into a get method.

              – Håken Lid
              Nov 10 '18 at 15:19


















            8





            +50









            You can have a path like path('pages/<str:page>, views.pages)



            And then in the view do something similar to:



            from django.template.loader import get_template
            from django.template import TemplateDoesNotExist

            def pages(request, page):
            template_name = f'your-app/{page}.html'
            try:
            get_template(template_name)
            return render(request, template_name)
            except TemplateDoesNotExist:
            # returns 404





            share|improve this answer


























            • Is this still the way to go? I thought ClassBasedViews are used today.

              – guettli
              Nov 7 '18 at 13:56






            • 1





              You can do it also with a class based view. But I think don't exist a generic class to do what you want to achieve. You will end up using simple view with a get method and the same body. So, in this case, is indifferent whatever you want to use.

              – grouchoboy
              Nov 7 '18 at 14:04













            • It does exist: extend TemplateView, then set template_name accordingly. However I think you then need to do the logic within get_context_data() which you overide.

              – v25
              Nov 7 '18 at 15:58








            • 1





              @V25 I think the problem with TemplateView is that it expects template_name to be a str and in this case, it should be evaluated based on the request param. So, at the end it would be more difficult and less clean to do the required modifications to leave working it, than use a simple View

              – grouchoboy
              Nov 7 '18 at 16:13








            • 2





              @guettli: There's no reason to prefer a class based view when you can write a function view that is concise and simple like this. It is possible (but pointless) to rewrite this as a class based view, by subclassing View and turning this function into a get method.

              – Håken Lid
              Nov 10 '18 at 15:19
















            8





            +50







            8





            +50



            8




            +50





            You can have a path like path('pages/<str:page>, views.pages)



            And then in the view do something similar to:



            from django.template.loader import get_template
            from django.template import TemplateDoesNotExist

            def pages(request, page):
            template_name = f'your-app/{page}.html'
            try:
            get_template(template_name)
            return render(request, template_name)
            except TemplateDoesNotExist:
            # returns 404





            share|improve this answer















            You can have a path like path('pages/<str:page>, views.pages)



            And then in the view do something similar to:



            from django.template.loader import get_template
            from django.template import TemplateDoesNotExist

            def pages(request, page):
            template_name = f'your-app/{page}.html'
            try:
            get_template(template_name)
            return render(request, template_name)
            except TemplateDoesNotExist:
            # returns 404






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 9 '18 at 17:49

























            answered Nov 7 '18 at 12:50









            grouchoboygrouchoboy

            46038




            46038













            • Is this still the way to go? I thought ClassBasedViews are used today.

              – guettli
              Nov 7 '18 at 13:56






            • 1





              You can do it also with a class based view. But I think don't exist a generic class to do what you want to achieve. You will end up using simple view with a get method and the same body. So, in this case, is indifferent whatever you want to use.

              – grouchoboy
              Nov 7 '18 at 14:04













            • It does exist: extend TemplateView, then set template_name accordingly. However I think you then need to do the logic within get_context_data() which you overide.

              – v25
              Nov 7 '18 at 15:58








            • 1





              @V25 I think the problem with TemplateView is that it expects template_name to be a str and in this case, it should be evaluated based on the request param. So, at the end it would be more difficult and less clean to do the required modifications to leave working it, than use a simple View

              – grouchoboy
              Nov 7 '18 at 16:13








            • 2





              @guettli: There's no reason to prefer a class based view when you can write a function view that is concise and simple like this. It is possible (but pointless) to rewrite this as a class based view, by subclassing View and turning this function into a get method.

              – Håken Lid
              Nov 10 '18 at 15:19





















            • Is this still the way to go? I thought ClassBasedViews are used today.

              – guettli
              Nov 7 '18 at 13:56






            • 1





              You can do it also with a class based view. But I think don't exist a generic class to do what you want to achieve. You will end up using simple view with a get method and the same body. So, in this case, is indifferent whatever you want to use.

              – grouchoboy
              Nov 7 '18 at 14:04













            • It does exist: extend TemplateView, then set template_name accordingly. However I think you then need to do the logic within get_context_data() which you overide.

              – v25
              Nov 7 '18 at 15:58








            • 1





              @V25 I think the problem with TemplateView is that it expects template_name to be a str and in this case, it should be evaluated based on the request param. So, at the end it would be more difficult and less clean to do the required modifications to leave working it, than use a simple View

              – grouchoboy
              Nov 7 '18 at 16:13








            • 2





              @guettli: There's no reason to prefer a class based view when you can write a function view that is concise and simple like this. It is possible (but pointless) to rewrite this as a class based view, by subclassing View and turning this function into a get method.

              – Håken Lid
              Nov 10 '18 at 15:19



















            Is this still the way to go? I thought ClassBasedViews are used today.

            – guettli
            Nov 7 '18 at 13:56





            Is this still the way to go? I thought ClassBasedViews are used today.

            – guettli
            Nov 7 '18 at 13:56




            1




            1





            You can do it also with a class based view. But I think don't exist a generic class to do what you want to achieve. You will end up using simple view with a get method and the same body. So, in this case, is indifferent whatever you want to use.

            – grouchoboy
            Nov 7 '18 at 14:04







            You can do it also with a class based view. But I think don't exist a generic class to do what you want to achieve. You will end up using simple view with a get method and the same body. So, in this case, is indifferent whatever you want to use.

            – grouchoboy
            Nov 7 '18 at 14:04















            It does exist: extend TemplateView, then set template_name accordingly. However I think you then need to do the logic within get_context_data() which you overide.

            – v25
            Nov 7 '18 at 15:58







            It does exist: extend TemplateView, then set template_name accordingly. However I think you then need to do the logic within get_context_data() which you overide.

            – v25
            Nov 7 '18 at 15:58






            1




            1





            @V25 I think the problem with TemplateView is that it expects template_name to be a str and in this case, it should be evaluated based on the request param. So, at the end it would be more difficult and less clean to do the required modifications to leave working it, than use a simple View

            – grouchoboy
            Nov 7 '18 at 16:13







            @V25 I think the problem with TemplateView is that it expects template_name to be a str and in this case, it should be evaluated based on the request param. So, at the end it would be more difficult and less clean to do the required modifications to leave working it, than use a simple View

            – grouchoboy
            Nov 7 '18 at 16:13






            2




            2





            @guettli: There's no reason to prefer a class based view when you can write a function view that is concise and simple like this. It is possible (but pointless) to rewrite this as a class based view, by subclassing View and turning this function into a get method.

            – Håken Lid
            Nov 10 '18 at 15:19







            @guettli: There's no reason to prefer a class based view when you can write a function view that is concise and simple like this. It is possible (but pointless) to rewrite this as a class based view, by subclassing View and turning this function into a get method.

            – Håken Lid
            Nov 10 '18 at 15:19













            0














            A simpler solution with django 2.x.



            Since you sound newer to django, this solution should be much easier. There's no reason to use f strings and try/except blocks with simple things. And I know when I started, class based views made no sense because there was no control flow.



            urls.py



            from django.urls import path
            from . import views

            app_name = 'article_app'

            urlpatterns = [
            path('', views.article_list, name='article_list'),
            path('new/', views.article_new, name='article_new'),
            path('<int:art_pk>/', views.article_detail, name='article_detail'),
            path('<int:art_pk>/update/', views.article_update, name='article_update'),
            path('<int:art_pk>/delete/', views.article_delete, name='article_delete'),
            # and so on....
            ]


            views.py



            from django.shortcuts import render
            from .models import Article

            def article_detail(request, art_pk):
            article = Article.objects.get(pk=art_pk)
            return render(request, 'articles_app/article_detail.html', {'article': article})


            template for article_detail.html



            {% block maincontent %}

            <div class="article">
            <h2><u>{{ article.title }}</u></h2>
            <h3>By: {{ article.author }} --- Posted / Updated on: {{ article.date }}</h3>
            <p>{{ article.body }}</p>
            <p><a href="{% url 'article_app:article_update' article.pk %}">Update</a> | <a href="{% url 'article_app:article_delete' article.pk %}">Delete</a></p>
            <p><a href="{% url 'article_app:article_list' %}">Back to all articles</a></p>
            </div>

            {% endblock maincontent %}








            If you had something more complicated:



            Lets say it's something that requires a few if/else statements to describe a Food model. Example:



            models.py



            class Food(models.Model):
            FLAVOR_CHOICES = (
            ('tasty', 'Very yummy'),
            ('disgusting', 'Nasty AF bro!'),
            ('super_sweet', 'For little kids'),
            ('bitter', 'Sure to grow hair on you balls!'),
            )
            food_choice = models.CharField(max_length=30, choices=FLAVOR_CHOICES, default='super_sweet')
            # and any other attribute for a Food


            urls.py



            app_name = 'food_app'

            urlpatterns = [
            # ....
            path('<int:food_id>/', views.show_food, name='show_food'),
            ]


            views.py



            def show_food(request, food_id):
            food = Food.objects.get(id=food_id)
            if food.food_choice == 'tasty':
            return render(request, 'food_app/food_stats.html', {'tasty': 'Everyone likes tasty things'})
            elif food.food_choice == 'bitter':
            return render(request, 'food_app/food_stats.html', {'bitter': 'Girls do not want to have balls. Sure way to end the gene pool.'})
            # .... and so on with other choices
            else:
            return render(request, 'food_app/food_stats.html')


            Then your food_stats.html template would look something like this



            Note that this should be used instead of creating separate pages for 'bitter.html', 'tasty.html', 'super_sweet.html', etc.



            {% block maincontent %}

            <h1>Your choice of food:</h1>

            {% if tasty %}
            <p>{{ tasty.food_choice }}</p> {# this attribute would show the 2nd value for 'tasty' in the tuple of FLAVOR_CHOICES - 'Very yummy' #}
            <p>{{ tasty }}</p> {# The value that shows here is the key I set in the view #}

            {% elif disgusting %}
            <p>{{ disgusting.food_choice }}</p>
            <p>{{ disgusting }}</p>

            {% elif super_sweet %}
            <p>{{ super_sweet.food_choice }}</p>
            <p>{{ super_sweet }}</p>

            {% elif bitter %}
            <p>{{ bitter.food_choice }}</p>
            <p>{{ bitter }}</p>

            {% else %}
            <p>No foods bro. You're lame.</p>

            {% endif %}

            {% endblock maincontent %}





            share|improve this answer


























            • Your answer starts with "a simpler solution". That's a good start. I see that the answer is very long. For me it is too long.

              – guettli
              Nov 16 '18 at 11:28






            • 1





              I was showing everything that's needed. Since you didn' seem to understand, I thought I'd teach you how it all works together. And if you understood everything but the templates, then just read the templates.

              – PwnSauceDesigns
              Nov 17 '18 at 14:44


















            0














            A simpler solution with django 2.x.



            Since you sound newer to django, this solution should be much easier. There's no reason to use f strings and try/except blocks with simple things. And I know when I started, class based views made no sense because there was no control flow.



            urls.py



            from django.urls import path
            from . import views

            app_name = 'article_app'

            urlpatterns = [
            path('', views.article_list, name='article_list'),
            path('new/', views.article_new, name='article_new'),
            path('<int:art_pk>/', views.article_detail, name='article_detail'),
            path('<int:art_pk>/update/', views.article_update, name='article_update'),
            path('<int:art_pk>/delete/', views.article_delete, name='article_delete'),
            # and so on....
            ]


            views.py



            from django.shortcuts import render
            from .models import Article

            def article_detail(request, art_pk):
            article = Article.objects.get(pk=art_pk)
            return render(request, 'articles_app/article_detail.html', {'article': article})


            template for article_detail.html



            {% block maincontent %}

            <div class="article">
            <h2><u>{{ article.title }}</u></h2>
            <h3>By: {{ article.author }} --- Posted / Updated on: {{ article.date }}</h3>
            <p>{{ article.body }}</p>
            <p><a href="{% url 'article_app:article_update' article.pk %}">Update</a> | <a href="{% url 'article_app:article_delete' article.pk %}">Delete</a></p>
            <p><a href="{% url 'article_app:article_list' %}">Back to all articles</a></p>
            </div>

            {% endblock maincontent %}








            If you had something more complicated:



            Lets say it's something that requires a few if/else statements to describe a Food model. Example:



            models.py



            class Food(models.Model):
            FLAVOR_CHOICES = (
            ('tasty', 'Very yummy'),
            ('disgusting', 'Nasty AF bro!'),
            ('super_sweet', 'For little kids'),
            ('bitter', 'Sure to grow hair on you balls!'),
            )
            food_choice = models.CharField(max_length=30, choices=FLAVOR_CHOICES, default='super_sweet')
            # and any other attribute for a Food


            urls.py



            app_name = 'food_app'

            urlpatterns = [
            # ....
            path('<int:food_id>/', views.show_food, name='show_food'),
            ]


            views.py



            def show_food(request, food_id):
            food = Food.objects.get(id=food_id)
            if food.food_choice == 'tasty':
            return render(request, 'food_app/food_stats.html', {'tasty': 'Everyone likes tasty things'})
            elif food.food_choice == 'bitter':
            return render(request, 'food_app/food_stats.html', {'bitter': 'Girls do not want to have balls. Sure way to end the gene pool.'})
            # .... and so on with other choices
            else:
            return render(request, 'food_app/food_stats.html')


            Then your food_stats.html template would look something like this



            Note that this should be used instead of creating separate pages for 'bitter.html', 'tasty.html', 'super_sweet.html', etc.



            {% block maincontent %}

            <h1>Your choice of food:</h1>

            {% if tasty %}
            <p>{{ tasty.food_choice }}</p> {# this attribute would show the 2nd value for 'tasty' in the tuple of FLAVOR_CHOICES - 'Very yummy' #}
            <p>{{ tasty }}</p> {# The value that shows here is the key I set in the view #}

            {% elif disgusting %}
            <p>{{ disgusting.food_choice }}</p>
            <p>{{ disgusting }}</p>

            {% elif super_sweet %}
            <p>{{ super_sweet.food_choice }}</p>
            <p>{{ super_sweet }}</p>

            {% elif bitter %}
            <p>{{ bitter.food_choice }}</p>
            <p>{{ bitter }}</p>

            {% else %}
            <p>No foods bro. You're lame.</p>

            {% endif %}

            {% endblock maincontent %}





            share|improve this answer


























            • Your answer starts with "a simpler solution". That's a good start. I see that the answer is very long. For me it is too long.

              – guettli
              Nov 16 '18 at 11:28






            • 1





              I was showing everything that's needed. Since you didn' seem to understand, I thought I'd teach you how it all works together. And if you understood everything but the templates, then just read the templates.

              – PwnSauceDesigns
              Nov 17 '18 at 14:44
















            0












            0








            0







            A simpler solution with django 2.x.



            Since you sound newer to django, this solution should be much easier. There's no reason to use f strings and try/except blocks with simple things. And I know when I started, class based views made no sense because there was no control flow.



            urls.py



            from django.urls import path
            from . import views

            app_name = 'article_app'

            urlpatterns = [
            path('', views.article_list, name='article_list'),
            path('new/', views.article_new, name='article_new'),
            path('<int:art_pk>/', views.article_detail, name='article_detail'),
            path('<int:art_pk>/update/', views.article_update, name='article_update'),
            path('<int:art_pk>/delete/', views.article_delete, name='article_delete'),
            # and so on....
            ]


            views.py



            from django.shortcuts import render
            from .models import Article

            def article_detail(request, art_pk):
            article = Article.objects.get(pk=art_pk)
            return render(request, 'articles_app/article_detail.html', {'article': article})


            template for article_detail.html



            {% block maincontent %}

            <div class="article">
            <h2><u>{{ article.title }}</u></h2>
            <h3>By: {{ article.author }} --- Posted / Updated on: {{ article.date }}</h3>
            <p>{{ article.body }}</p>
            <p><a href="{% url 'article_app:article_update' article.pk %}">Update</a> | <a href="{% url 'article_app:article_delete' article.pk %}">Delete</a></p>
            <p><a href="{% url 'article_app:article_list' %}">Back to all articles</a></p>
            </div>

            {% endblock maincontent %}








            If you had something more complicated:



            Lets say it's something that requires a few if/else statements to describe a Food model. Example:



            models.py



            class Food(models.Model):
            FLAVOR_CHOICES = (
            ('tasty', 'Very yummy'),
            ('disgusting', 'Nasty AF bro!'),
            ('super_sweet', 'For little kids'),
            ('bitter', 'Sure to grow hair on you balls!'),
            )
            food_choice = models.CharField(max_length=30, choices=FLAVOR_CHOICES, default='super_sweet')
            # and any other attribute for a Food


            urls.py



            app_name = 'food_app'

            urlpatterns = [
            # ....
            path('<int:food_id>/', views.show_food, name='show_food'),
            ]


            views.py



            def show_food(request, food_id):
            food = Food.objects.get(id=food_id)
            if food.food_choice == 'tasty':
            return render(request, 'food_app/food_stats.html', {'tasty': 'Everyone likes tasty things'})
            elif food.food_choice == 'bitter':
            return render(request, 'food_app/food_stats.html', {'bitter': 'Girls do not want to have balls. Sure way to end the gene pool.'})
            # .... and so on with other choices
            else:
            return render(request, 'food_app/food_stats.html')


            Then your food_stats.html template would look something like this



            Note that this should be used instead of creating separate pages for 'bitter.html', 'tasty.html', 'super_sweet.html', etc.



            {% block maincontent %}

            <h1>Your choice of food:</h1>

            {% if tasty %}
            <p>{{ tasty.food_choice }}</p> {# this attribute would show the 2nd value for 'tasty' in the tuple of FLAVOR_CHOICES - 'Very yummy' #}
            <p>{{ tasty }}</p> {# The value that shows here is the key I set in the view #}

            {% elif disgusting %}
            <p>{{ disgusting.food_choice }}</p>
            <p>{{ disgusting }}</p>

            {% elif super_sweet %}
            <p>{{ super_sweet.food_choice }}</p>
            <p>{{ super_sweet }}</p>

            {% elif bitter %}
            <p>{{ bitter.food_choice }}</p>
            <p>{{ bitter }}</p>

            {% else %}
            <p>No foods bro. You're lame.</p>

            {% endif %}

            {% endblock maincontent %}





            share|improve this answer















            A simpler solution with django 2.x.



            Since you sound newer to django, this solution should be much easier. There's no reason to use f strings and try/except blocks with simple things. And I know when I started, class based views made no sense because there was no control flow.



            urls.py



            from django.urls import path
            from . import views

            app_name = 'article_app'

            urlpatterns = [
            path('', views.article_list, name='article_list'),
            path('new/', views.article_new, name='article_new'),
            path('<int:art_pk>/', views.article_detail, name='article_detail'),
            path('<int:art_pk>/update/', views.article_update, name='article_update'),
            path('<int:art_pk>/delete/', views.article_delete, name='article_delete'),
            # and so on....
            ]


            views.py



            from django.shortcuts import render
            from .models import Article

            def article_detail(request, art_pk):
            article = Article.objects.get(pk=art_pk)
            return render(request, 'articles_app/article_detail.html', {'article': article})


            template for article_detail.html



            {% block maincontent %}

            <div class="article">
            <h2><u>{{ article.title }}</u></h2>
            <h3>By: {{ article.author }} --- Posted / Updated on: {{ article.date }}</h3>
            <p>{{ article.body }}</p>
            <p><a href="{% url 'article_app:article_update' article.pk %}">Update</a> | <a href="{% url 'article_app:article_delete' article.pk %}">Delete</a></p>
            <p><a href="{% url 'article_app:article_list' %}">Back to all articles</a></p>
            </div>

            {% endblock maincontent %}








            If you had something more complicated:



            Lets say it's something that requires a few if/else statements to describe a Food model. Example:



            models.py



            class Food(models.Model):
            FLAVOR_CHOICES = (
            ('tasty', 'Very yummy'),
            ('disgusting', 'Nasty AF bro!'),
            ('super_sweet', 'For little kids'),
            ('bitter', 'Sure to grow hair on you balls!'),
            )
            food_choice = models.CharField(max_length=30, choices=FLAVOR_CHOICES, default='super_sweet')
            # and any other attribute for a Food


            urls.py



            app_name = 'food_app'

            urlpatterns = [
            # ....
            path('<int:food_id>/', views.show_food, name='show_food'),
            ]


            views.py



            def show_food(request, food_id):
            food = Food.objects.get(id=food_id)
            if food.food_choice == 'tasty':
            return render(request, 'food_app/food_stats.html', {'tasty': 'Everyone likes tasty things'})
            elif food.food_choice == 'bitter':
            return render(request, 'food_app/food_stats.html', {'bitter': 'Girls do not want to have balls. Sure way to end the gene pool.'})
            # .... and so on with other choices
            else:
            return render(request, 'food_app/food_stats.html')


            Then your food_stats.html template would look something like this



            Note that this should be used instead of creating separate pages for 'bitter.html', 'tasty.html', 'super_sweet.html', etc.



            {% block maincontent %}

            <h1>Your choice of food:</h1>

            {% if tasty %}
            <p>{{ tasty.food_choice }}</p> {# this attribute would show the 2nd value for 'tasty' in the tuple of FLAVOR_CHOICES - 'Very yummy' #}
            <p>{{ tasty }}</p> {# The value that shows here is the key I set in the view #}

            {% elif disgusting %}
            <p>{{ disgusting.food_choice }}</p>
            <p>{{ disgusting }}</p>

            {% elif super_sweet %}
            <p>{{ super_sweet.food_choice }}</p>
            <p>{{ super_sweet }}</p>

            {% elif bitter %}
            <p>{{ bitter.food_choice }}</p>
            <p>{{ bitter }}</p>

            {% else %}
            <p>No foods bro. You're lame.</p>

            {% endif %}

            {% endblock maincontent %}






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 14 '18 at 1:52

























            answered Nov 14 '18 at 0:27









            PwnSauceDesignsPwnSauceDesigns

            263110




            263110













            • Your answer starts with "a simpler solution". That's a good start. I see that the answer is very long. For me it is too long.

              – guettli
              Nov 16 '18 at 11:28






            • 1





              I was showing everything that's needed. Since you didn' seem to understand, I thought I'd teach you how it all works together. And if you understood everything but the templates, then just read the templates.

              – PwnSauceDesigns
              Nov 17 '18 at 14:44





















            • Your answer starts with "a simpler solution". That's a good start. I see that the answer is very long. For me it is too long.

              – guettli
              Nov 16 '18 at 11:28






            • 1





              I was showing everything that's needed. Since you didn' seem to understand, I thought I'd teach you how it all works together. And if you understood everything but the templates, then just read the templates.

              – PwnSauceDesigns
              Nov 17 '18 at 14:44



















            Your answer starts with "a simpler solution". That's a good start. I see that the answer is very long. For me it is too long.

            – guettli
            Nov 16 '18 at 11:28





            Your answer starts with "a simpler solution". That's a good start. I see that the answer is very long. For me it is too long.

            – guettli
            Nov 16 '18 at 11:28




            1




            1





            I was showing everything that's needed. Since you didn' seem to understand, I thought I'd teach you how it all works together. And if you understood everything but the templates, then just read the templates.

            – PwnSauceDesigns
            Nov 17 '18 at 14:44







            I was showing everything that's needed. Since you didn' seem to understand, I thought I'd teach you how it all works together. And if you understood everything but the templates, then just read the templates.

            – PwnSauceDesigns
            Nov 17 '18 at 14:44













            0














            from django.conf.urls import url
            from .import views



            urlpatterns = [
            # url(r'^/$', views.function_name, name="Page")



            url(r'^$', views.home, name="Home Page"),


            ]



            use this patterns match to show your .html pages






            share|improve this answer




























              0














              from django.conf.urls import url
              from .import views



              urlpatterns = [
              # url(r'^/$', views.function_name, name="Page")



              url(r'^$', views.home, name="Home Page"),


              ]



              use this patterns match to show your .html pages






              share|improve this answer


























                0












                0








                0







                from django.conf.urls import url
                from .import views



                urlpatterns = [
                # url(r'^/$', views.function_name, name="Page")



                url(r'^$', views.home, name="Home Page"),


                ]



                use this patterns match to show your .html pages






                share|improve this answer













                from django.conf.urls import url
                from .import views



                urlpatterns = [
                # url(r'^/$', views.function_name, name="Page")



                url(r'^$', views.home, name="Home Page"),


                ]



                use this patterns match to show your .html pages







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 7:15









                KUNTAL SAMANTAKUNTAL SAMANTA

                61




                61






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53188920%2fdjango-20-html-files-20-templateviews-and-20-url-patterns-needed%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    The Sandy Post

                    Danny Elfman

                    Pages that link to "Head v. Amoskeag Manufacturing Co."