Josh
Josh

Reputation: 285

Django Modelform Redirect to form-submitted content

Disclaimer: Still very new at this.

I've managed to get a site up and running that catalogs rock climbs. I've got a functioning form that allows users to submit a new item to the catalog, but have been unable to figure out how to redirect them to the newly created page. Here's my code:

("..." in place of what I think is irrelevant and bulky code. Let me know if you need it in!)

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)

and urls.py:

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

Right now i Just have it redirecting to a static html page because I can't figure out how to get it to load the newly created page. I've tried using the redirect function, but am unsure how to designate the newly created page as the destination.

Thank you!

Edit: Here is the working code:

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})

Upvotes: 0

Views: 1812

Answers (1)

arcegk
arcegk

Reputation: 1480

From the docs

You can use the redirect shortcut and reverse function to reverse-resolve the name, in your case:

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

Upvotes: 1

Related Questions