Search code examples
djangodjango-formsget

How to send a user to a particular URL using a form in Django


I'd like users to be able to select from a form a user and then be directed to individual/user_slug. Currently, I am redirecting to individual?slug=user_slug. I cant figure out if I need to change something with the HTML form, url mapping, or the view itself. Any help or guidance would be appreciated!

HTML form

  <form action="individual" method="get">
    <label for="slug">Choose a person:</label>
    <select id="slug" name="slug">
      <option value="person_a_slug">Person A</option>
      <option value="person_b_slug">Person B</option>
      <option value="person_c_slug">Person C</option>
    </select>
    <input type="submit">
  </form>

urls.py

urlpatterns = [
    path('individual/<slug:slug>', IndividualView.as_view(), name = 'individual'),
    path('', HomePageView.as_view(), name='home'),
]

views.py

class HomePageView(ListView): 
    model = Person
    template_name = 'home.html'


class IndividualView(DetailView):
    model = Person
    template_name = 'individual.html'

models.py

class Person(models.Model):
    name = models.CharField(max_length=200)

    description = models.TextField()

    slug = models.SlugField(null=True, unique=True)

    photo = models.URLField(null=True)

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

Solution

  • It seems like the onClick attribute was what I was looking for.

    The below HTML gets exactly what I wanted.

      <form name="jump">
        <label for="slug">Choose a person:</label>
        <select name="menu">
          <option value="person_a_slug">Person A</option>
          <option value="person_b_slug">Person B</option>
          <option value="person_c_slug">Person C</option>
        </select>
        <input type="button" onClick="location='individual/' + document.jump.menu.options[document.jump.menu.selectedIndex].value;">
    
      </form>