A
A
alex_deerk2016-07-20 19:23:29
Django
alex_deerk, 2016-07-20 19:23:29

Django how to pass parameter from template context to url?

Sample:

<form action="{% url 'new_item' category=category %}" method="post">

Urls:
url(r'^new/(?P<category>[\w\-]+)/$', views.new_item, name='new_item'),

Performance:
def new_item(req, category=''):
args = dict()
args.update(csrf(req))
if req.method == 'POST':
    if category == 'phone':
        form = PhoneForm(req.POST, req.FILES)
        if form.is_valid():
            form.save()
            return redirect('general')
        else:
            args['form'] = form
            return render_to_response('new_item/index.html', args)
else:
    if category == 'phone':
        args['form'] = PhoneForm()
        args['category'] = 'phone'
return render_to_response('new_item/index.html', args)

Moreover, for a regular link, such a code works, but not for form
<a href="{% url 'new_item' category=category %}"></a>

Mistake:

NoReverseMatch at /adminpanel/new/phone/ Reverse for 'new_item' with arguments '()' and keyword arguments '{'category': ''}' not found. 1 pattern(s) tried: ['adminpanel/new/(?P[\w\-]+)/$']

На данный момент передаю в контекст url через reverse во въюшке, но хотелось бы понять.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Влад, 2016-07-20
@d1skort

Так в ветке POST во вьюшке category не передается в контекст.

S
swansong, 2016-07-21
@swansong

It can be seen from the error that category is not defined in the template, and reverse cannot find a suitable entry in urlconf because an empty category does not match the regular expression (?P[\w\-]+).
How do you form the url in the view?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question