Django Modelform重定向到表单提交的内容

时间:2017-02-04 03:48:48

标签: python django forms redirect

免责声明:此处仍然很新。

我设法让一个网站启动并运行目录攀岩。我有一个功能正常的表单,允许用户向目录提交新项目,但无法弄清楚如何将它们重定向到新创建的页面。这是我的代码:

(" ......"取代我认为无关紧要和笨重的代码。如果你需要它,请告诉我!)

forms.py:

class PostForm(forms.ModelForm):
    class Meta:
        model = MyDB
        fields = (...)
    def save(self):
        instance = super(PostForm, self).save(commit=False)
        instance.slug = slugify (instance.name)
        instance.save()

        return instance

views.py:

def post_new(request):
    things = MyDB.objects.order_by('name')
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            created_at = timezone.now()
            updated_at = timezone.now()
            form.save()
            return render(request, 'DB.html', {
                'things': things,
            })
    else:
        form = PostForm()
    return render(request, 'things/submit_thing.html', {'form': form})

models.py:

from django.db import models

class MyDB(models.Model):
    ...
    slug = models.SlugField(unique=True)

和urls.py:

url(r'^things/(?P<slug>[-\w]+)/$', views.thing_detail, name='thing_detail'),
url(r'^post/new/$', views.post_new, name='post_new'),

现在我只是将它重定向到静态html页面,因为我无法弄清楚如何让它加载新创建的页面。我已尝试使用重定向功能,但不确定如何将新创建的页面指定为目标。

谢谢!

编辑:这是工作代码:

from django.shortcuts import render, redirect, reverse

def post_new(request):
    things = MyDB.objects.order_by('name')
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            created_at = timezone.now()
            updated_at = timezone.now()
            thing = form.save()    
            return redirect(reverse('thing_detail', kwargs={'slug': thing.slug})
            )
    else:
        form = PostForm()
    return render(request, 'things/submit_thing.html', {'form': form})

1 个答案:

答案 0 :(得分:0)

来自docs

在您的情况下,您可以使用redirect快捷方式和reverse功能反向解析名称:

thing = form.save()    
redirect(reverse('thing_detail', kwargs={'slug': thing.slug))