[Django]-Django โ€“ url tag not working

1๐Ÿ‘

โœ…

Seems like you donโ€™t need any parameters to {% url %} in your template.

You can add function to your views.py for creating questions, that will redirect user to question page after success:

urls.py:

url(r'^neues_thema/', 'home.views.create_question', name="create_question"),
url(r'^neues_thema/(?P<title>\w+)/', 'home.views.question', name="question"),

views.py:

from django.core.urlresolvers import reverse
from django.shortcuts import render

def create_question(request):
    if request.method == 'POST':
        title = request.POST['title']
        # some validation of title
        # create new question with title
        return redirect(reverse('question', kwargs={'title': title})


def question(request, title):
    # here smth like: 
    # question = get_object_or_404(Question, title=title)
    return render(request, 'question.html', {'question': question})

template with form for creating question:

<form action="{% url create_question %}" method="post">

Answering your โ€œwhat am i doing wrong?โ€. You are trying to render url by mask neues_thema/(\w+)/ with this: {% url create_question %}. Your mask needs some parameter ((\w+)), but you are putting no parameter. Rendering with parameter should be {% url create_question title %}. But the problem is: you donโ€™t know the title while rendering page.

๐Ÿ‘คimkost

3๐Ÿ‘

Your url regular expression expects a parameter, your template should be like:

<form action="{% url create_question some_user_name %}" method="post">

See url on Built-in template tags and filters docs

๐Ÿ‘คdani herrera

2๐Ÿ‘

You can do:

url(r'^neues_thema/(?P<user>\w*)$','home.views.create_question',name="create_question"),

and in your views

def create_question(request, user=None):
๐Ÿ‘คkarthikr

0๐Ÿ‘

Write it like this {% url 'home.views.create_question' alhphanumeric_work %}. It should work.

Leave a comment