Error creating routes dynamically in Django

Asked

Viewed 53 times

-2

of good? Next, taking my first steps with Framework Django and having some difficulties, some managed to overcome "alone", this bone. I have a basic blog project with some views, in which shows the details of the article all tags are anchors, but it’s not going the way it should, the template is like this >>

    {% extends 'base.html' %} {% block head_title %} {{ Post.Title }} {% endblock %} {% block content %}

<div class="row">

    <div class="col-md-8 right-sidebar">

        <div class="row">

            <div class="post-19 post type-post status-publish format-standard hentry category-uncategorized tag-boat tag-lake post-container col-md-12">


                <div class="post-article post-details post-details-1  ">

                    <h1 class="title">{{Post.Title}}</h1>
                    <div class="line">

                        <div class="entry-info">

                            <span>
                                    <i class="fa fa-clock-o"></i>
                                    {{Post.Created_at}}
                                </span>

                        </div>

                    </div>

                    <div style="width: 445px" class="wp-caption alignnone">
                        <img class="wp-image-59" alt="Thumbnail" src="{{Post.Thumbnail.url}}" width="435" height="288">
                    </div>

                    {{Post.Content | safe }}

                    <footer class="line">
                        <span class="entry-info">
                            <i class="fa fa-tags" aria-hidden="true"></i>
                            <strong>Tags:</strong>
                            {% for tag in Post.Tag.all %}
                            <a href="{% url 'Blog:fortag' slug=tag.slug }" class="mr-1 balde balde-info">{{ tag }}</a> 
                            {% endfor %}
                        </span> 

                    </footer>
                </div>

            </div>

        </div>

    </div>


    <div id="sidebar" class="col-md-4 sidebar-area">

        <div class="post-container">

            <div class="post-article">

                <div class="widget-box widget_calendar">
                    <h4 class="title">Calendário</h4>
                    <div id="calendar_wrap" class="calendar_wrap">
                        <SCRIPT LANGUAGE="JavaScript">
                            var day_of_week = new Array('Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab');
                            var month_of_year = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');

                            var Calendar = new Date();

                            var year = Calendar.getYear(); // Retorna o ano
                            var month = Calendar.getMonth(); // Retorna mes (0-11)
                            var today = Calendar.getDate(); // Retorna dias (1-31)
                            var weekday = Calendar.getDay(); // Retorna dias (1-31)

                            var DAYS_OF_WEEK = 7; // "constant" para o numero de dias na semana
                            var DAYS_OF_MONTH = 31; // "constant" para o numero de dias no mes
                            var cal; // Usado para imprimir na tela

                            Calendar.setDate(1); // Comecar o calendario no dia '1'
                            Calendar.setMonth(month); // Comecar o calendario com o mes atual


                            var TR_start = '<TR>';
                            var TR_end = '</TR>';
                            var highlight_start = '<TD WIDTH="30"><TABLE CELLSPACING=0 BORDER=1 BGCOLOR=DEDEFF BORDERCOLOR=CCCCCC><TR><TD WIDTH=20><B><CENTER>';
                            var highlight_end = '</CENTER></TD></TR></TABLE></B>';
                            var TD_start = '<TD WIDTH="30"><CENTER>';
                            var TD_end = '</CENTER></TD>';

                            cal = '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';
                            cal += '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=2>' + TR_start;
                            cal += '<TD COLSPAN="' + DAYS_OF_WEEK + '" BGCOLOR="#F2F2F2"><CENTER><B>';
                            cal += month_of_year[month] + '   ' + year + '</B>' + TD_end + TR_end;
                            cal += TR_start;

                            for (index = 0; index < DAYS_OF_WEEK; index++) {

                                if (weekday == index)
                                    cal += TD_start + '<B>' + day_of_week[index] + '</B>' + TD_end;
                                else
                                    cal += TD_start + day_of_week[index] + TD_end;
                            }

                            cal += TD_end + TR_end;
                            cal += TR_start;

                            for (index = 0; index < Calendar.getDay(); index++)
                                cal += TD_start + '  ' + TD_end;

                            for (index = 0; index < DAYS_OF_MONTH; index++) {
                                if (Calendar.getDate() > index) {
                                    week_day = Calendar.getDay();
                                    if (week_day == 0)
                                        cal += TR_start;
                                    if (week_day != DAYS_OF_WEEK) {
                                        var day = Calendar.getDate();
                                        if (today == Calendar.getDate())
                                            cal += highlight_start + day + highlight_end + TD_end;
                                        else
                                            cal += TD_start + day + TD_end;
                                    }
                                    if (week_day == DAYS_OF_WEEK)
                                        cal += TR_end;
                                }
                                Calendar.setDate(Calendar.getDate() + 1);
                            }
                            cal += '</TD></TR></TABLE></TABLE>';

                            //  MOSTRAR CALENDARIO
                            document.write(cal);
                            //  End -->
                        </SCRIPT>
                        <!-- <nav aria-label="Previous and next months" class="wp-calendar-nav">
                                <span class="wp-calendar-nav-prev"><a href="#">« Oct</a></span>
                                <span class="pad">&nbsp;</span>
                                <span class="wp-calendar-nav-next">&nbsp;</span>
                            </nav> -->
                    </div>
                </div>
                <div class="widget-box widget_archive">
                    <h4 class="title">Arquivos</h4>
                    <ul>
                        <li><a href="#">Outubro 2008</a></li>
                        <li><a href="#">Setembro 2008</a></li>
                        <li><a href="#">Junho 2008</a></li>
                    </ul>
                </div>

                <div class="section" id="sidebar-author">
                    <div class="widget Text" data-version="1" id="Text1">
                        <h2 class="title">
                            <span>Sobre o autor</span>
                        </h2>
                        <div class="widget-content">
                            <div class="widget-content">
                                <center>
                                    <div class="photo-profile">
                                        <img alt="Avatar do/da autor(a)" class="image wp-image-139  attachment-medium size-medium" height="300" sizes="(max-width: 300px) 100vw, 300px" src="{{user.Photo}}">
                                        <br>
                                    </div>
                                    <br>
                                    <br>
                                    <h2>
                                        <span>
                                                <span>{{Post.Author}}</span>
                                        </span>
                                    </h2>
                                    <p>"{{user.Biografy}}"</p>
                                </center>
                                <br>
                            </div>
                        </div>
                        <div class="clear">
                        </div>
                    </div>

                </div>

            </div>

        </div>

    </div>
</div>

{% endblock %}

The views >>

    def fortag(request, slug):

    tag = get_object_or_404(Tag, slug = slug)

    posts = Article.object.filter(Tag = tag)

    context = {
        'tag' : tag,
        'posts' : posts
    }

    return render(request, 'fortag.html', context)


def post(request, pk):

    Post = get_object_or_404(Article, pk=pk)

    return render(request, 'post.html', {'Post': Post})

Models >>

from taggit.managers import TaggableManager

from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField

from django.contrib.auth.models import User
from django.db import models

class Article(models.Model):

    Thumbnail = models.ImageField(upload_to='thumb/')
    Title = models.CharField(max_length=255, blank=False, help_text='Nome do post')
    Created_at = models.DateField(auto_now_add=True)
    Summary = RichTextField(blank=False)
    Content = RichTextUploadingField(blank=False)
    Tag = TaggableManager()
    Author = models.ForeignKey(User, on_delete=models.PROTECT, blank=False)

    class Meta:
        verbose_name_plural = 'Posts'

    def __str__(self):
        return self.Title

And the app urls >>

from django.urls import path, include

from django.conf.urls.static import static
from django.conf import settings

from .views import home, sobre, post, fortag

app_name = 'Blog'

urlpatterns = [
    path('', home, name= 'home'),
    path('sobre/', sobre),
    path('post/<int:pk>/', post, name = 'post'),
    path('tag/<slug:slug>/', fortag, name='fortag'),
    path('/ckeditor/', include('ckeditor_uploader.urls')),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

The error that appears is this >> inserir a descrição da imagem aqui

Someone knows how to fix it and can help me, please?

  • You have to improve some details about your doubt, you have that error when you try to load that template, or when you click a button, but it doesn’t indicate if it’s the post.html or fortag.html, it looks like fortag.html to me, but you have to indicate that. Note that {% url 'Blog:fortag' Slug=tag.Slug } appears after post/2/, this route does not exist in your urls.py file, I return to the initial question, as in the error, by clicking on a generated button or rendering fortag.html?

  • It happens when I click on a generated button, in the case of tag...

  • If you do an Inspection in the browser, you will see that what you are generating on the routes is localhost:8000/post/[ID]/{% url 'Blog:fortag' Slug=tag.Slug }, right?

  • If you have your project versioned, github for example share access to analyze what’s going on, you lack parts of your code to try to analyze...for example from taggit.managers import Taggablemanager, in your models.py.

  • It is partially complete in https://github.com/Natanapps/blogdjango

1 answer

0


Your problem is missing '%' at tag close, put that line in place of your.

<a href="{% url 'Blog:fortag' slug=tag.slug %}" class="mr-1 balde balde-info"> {{ tag }} </a>

Additionally, in your.py views the line changes:

posts = Article.object.filter(Tag = tag)

for

posts = Article.objects.filter(Tag = tag)
  • Thanks, that’s all it was. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.