[Django]-Form preview in Django

4👍

When someone reaches your index page and enters the form we need to

  1. Submit the form as a POST request to index view
  2. Save the form thereby creating a model in the DB
  3. Redirect the user to preview view using the above id

To do that the code needs to be somewhat like this, I have not tested it, but you should get the idea.

from django.shortcuts import redirect

def index(request):
    form = RegisterForm()
    if request.method == 'POST':
        form = RegisterForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save()
            return redirect('preview', pk=instance.id)
    context = {'form':form}
    return render(request, 'event/index.html', context)

Inside your index.html change

action="{% url 'preview' form.id %}"

to

action=""

as we want it to post to the INDEX view as that is where out POST handling logic is.

The index view then redirects to preview using the newly generated object.

Also as mentioned by @Snir in the other answer, having .html in URLS is not a standard practice. It would be better to simple make it something like:

path('preview/<str:pk>', views.preview, name="preview")

1👍

The URL patterns are regexes, so you’ll have to escape special regex characters, like the dot. Try (add r) or remove the dot:

    path(r'preview.html/<str:pk>', views.preview, 
    name="preview")

Leave a comment