TypeError show_poll() got an unexpected keyword argument 's'

Viewed 207

I'm trying to redirect the user after submitting a form to the polls list. The form is saved in the admin after submitting but the redirection is failing anyone can help me with this?

My views.py:

def show_poll(request, id):

  p = Poll.objects.get(id=id)
  pops = p.option_set.all()
  context = {
    'poll': p,
    'options': pops,
  }
  return render(request, "show_poll.html", context)

def create_poll(request):

  c_form = PollForm(request.POST or None)
  data = {}
  data["create_form"] = c_form
  if c_form.is_valid():
    poll = c_form.save(commit=False)
    poll.slug = slugify(poll.title)
    poll.save()
    return redirect("show_poll", s=poll.slug)
  return render(request, "create_poll.html", context=data)

My urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('show/poll/<int:id>/', views.show_poll, name="show_polls"),
    path('c_poll/<slug:s>/',views.show_poll, name="show_poll"),
    path('create/poll/',views.create_poll)
]
1 Answers

You have two paths that refer to the same view, indeed:

path('show/poll/<int:id>/', views.show_poll, name='show_polls'),
path('c_poll/<slug:s>/',views.show_poll, name='show_poll'),

This thus means that the show_poll can be called by the first or second pattern. In case of the first one, it will call this with id, and without an s.

If the second pattern "fires", then it will cal show_poll with s=… with … the slug.

You can perhaps combine the two and work with:

from django.shortcuts import get_object_or_404

def show_poll(request, id=None, s=None):
    qs = Poll.objects.all()
    if id is not None:
        qs = qs.filter(pk=id)
    if s is not None:
        qs = qs.filter(slug=s)
    p = get_object_or_404(qs)
    pops = p.option_set.all()
    context = {
        'poll': p,
        'options': pops,
    }
    return render(request, "show_poll.html", context)

another option is to make two separate views, one for the first pattern and one for the other pattern.

Related