【问题标题】:URL Redirection is not working (Django 3.0)URL 重定向不起作用(Django 3.0)
【发布时间】:2020-05-28 05:56:26
【问题描述】:

我是写编程的新手,现在我正在学习 django。 我有一个 URL 重定向问题。我创建了模型,它确实在管理站点工作。 我还为每篇文章设置了PK,通过PK成功生成URL。
但是,当我从前端发布消息时,在发布后出现错误消息假设它应该重定向到 DetailViewand 的页面 我在我的模型中导入了反向函数,但它似乎不起作用。 我的 python 版本:3.7.6 和 django 版本:3.0.0

ImproperlyConfigured at /add/
No URL to redirect to.  Either provide a url or define a get_absolute_url method on the Model.
My View
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView
from .models import Page


class PageListView(ListView):
    model = Page
    template_name='home.html'
    context_object_name = 'all_post_list'

class PageDetailView(DetailView):
    model = Page
    template_name='post.html'

class PageCreateView(CreateView):
    model = Page
    template_name='post_new.html'
    fields = ['title', 'author', 'body', 'body2']
Model

from django.urls import reverse
from django.db import models
from ckeditor.fields import RichTextField


class Page(models.Model):
    title = models.CharField(max_length=50)
    author = models.ForeignKey(
        'auth.User',  
        on_delete=models.CASCADE,
        )
    body = RichTextField()
    body2 = models.TextField()

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post', args=[str(self.id)])
URL
from django.urls import path
from .views import PageListView, PageDetailView, PageCreateView

urlpatterns = [
    path('add/', PageCreateView.as_view(), name='post_new'),
    path('', PageListView.as_view(), name='home'),
    path('blog/<int:pk>/', PageDetailView.as_view(), name='post'),
]

感谢您的帮助。 :)

【问题讨论】:

    标签: python django


    【解决方案1】:

    我认为您的缩进是这里的问题。修复它:

    class Page(models.Model):
        title = models.CharField(max_length=50)
        author = models.ForeignKey(
            'auth.User',  
            on_delete=models.CASCADE,
            )
        body = RichTextField()
        body2 = models.TextField()
    
        def __str__(self):
            return self.title
    
        def get_absolute_url(self):
            return reverse('post', args=[self.id])
    

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 2014-05-21
      • 2014-08-30
      • 2014-11-22
      • 2018-05-14
      • 2017-07-05
      • 1970-01-01
      相关资源
      最近更新 更多