简体   繁体   中英

django - url tag not working

I have this form:

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

and this url.py

url(r'^neues_thema/(\w+)/','home.views.create_question',name="create_question"),

but I am getting this error:

Reverse for 'create_question' with arguments '()'
 and keyword arguments '{}' not found.

what am i doing wrong?

EDIT : what i want to do is: the user submits the form, and i want to take the titel of question which user is creating and put it into url. then url will look like: neues_thema/how-to-make-bread/ . how can i give that parameter to {% url create_question ??? %} {% url create_question ??? %} dynamically while submitting the form

this thread url template tag in django template didnot help me.

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM