CreateView + get_absolute_url

时间:2019-02-12 04:18:07

标签: django python-3.x django-models orm django-views

我正在尝试使用CreateView,这是一些问题,我正在将其堆叠。

enter code here

首先,我正在尝试创建帖子并动态填充创建帖子的用户字段。它保存了帖子,但不保存用户:

图片来自管理员

enter image description here

#views.py

    class PostCreateView(CreateView):
        model = Post
        template_name = 'blog/post_create.html'
        fields = ('title', 'slug', 'body',)

        def form_valid(self, form):
            form.instance.blog__user = self.request.user
            return super(PostCreateView,self).form_valid(form)

#models.py

第二个问题,我认为是主要问题,我没有正确使用get_absolute_url,却遇到了这个问题:

没有要重定向到的URL。

enter image description here

但这对post_detail很有用。

     class Blog(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        slug = models.SlugField(max_length=50)


        def __str__(self):
            return self.user.username

def create_blog(sender, **kwargs):
    if kwargs['created']:
        user_blog = Blog.objects.create(user=kwargs['instance'], slug=kwargs['instance'])

post_save.connect(create_blog, sender=User)

class Post(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    slug = models.SlugField(max_length=50, db_index=True)
    title = models.CharField(max_length=120, db_index=True)
    body = models.TextField(blank=True, db_index=True)
    pub_date = models.DateTimeField(auto_now_add=True)

    def get_absolute_url(self):
        return reverse('post_detail_url', kwargs={'slug': self.slug,
                                                'username': self.blog})

#urls.py

urlpatterns = [
    path('<username>/create/', PostCreateView.as_view(), name='post_create'),
    path('<username>/<str:slug>/', PostDetailView.as_view(), name='post_detail_url'),
    path('<username>/', PostListView.as_view(), name='post_list_url'),
    path('<username>/<str:slug>/update/', PostUpdateView.as_view(), name='post_update'),

]

我试图定义get_success_url,我得到了这个:NoReverseMatch

enter image description here

请帮助我,我真的迷失在云端!

1 个答案:

答案 0 :(得分:0)

尝试下面的代码

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[usp_SetRecordCheckStatus]
    @pIntRecordKeyValue INT,
    @pIntCheckBoxStatus INT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE dbo.Record
        SET CheckState = @pIntCheckBoxStatus
        WHERE Pno = @pIntCheckBoxStatus
END
GO