Reverse match URL in Django 1.5 - django

I have a URL defined like this in Django:
# http://localhost:8000/quiz/grammar/beginner/1/question
url(r'^(?P<page_name>[-\w]+)/(?P<level>\w+)/(?P<quiz_id>\d+)/question/$', views.question, name='question')
If I pass the static values I don't get any errors:
{{ i.name }}
Since I am already on this page: http://localhost:8000/quiz/grammar/beginner/ I thought of passing URL like this:
{% for i in quizes %}
{{ i.name }}
{% endfor %}
I have namespace defined. But I get this error:
Reverse for 'question' with arguments '(1L,)' and keyword arguments '{}' not found.
I am doing like this in my view:
def question(request, quiz_id):
What's wrong?
EDIT: Tried this, still no luck:
def question(request, page_name, level, quiz_id):

The url tag returns an absolute url. It is not aware of the page your are on, so you cannot leave out the the level and quiz arguments when using the tag.
If you have page_name and level in your template context, you can use these variables in the url tag.
{{ i.name }}
If you capture page_name and level arguments in your url, then you are correct to change your view function to accept them.
def question(request, page_name, level, quiz_id):

Related

Django / an argument with HttpResponseRedirect is empty in my HTML page

In Views.py
return HttpResponseRedirect('add_scenes?submitted=True?linkToPrevScene=%s'%ScenePrevious)
ScenePrevious is a string containing "water2"
In my URL of add_scenes.html it works :
http://127.0.0.1:8000/scenes3d/add_scenes?submitted=True?linkToPrevScene=water2
But in the file add_scenes.html
{% if submitted %}
your scene was submitted successfully after {{ linkToPrevScene }}
{% else %}
this HTML code doesn't give output for {{ linkToPrevScene }} although {% if submitted %} is evaluated correctly
edit of my post:
This line also doesn't work if I replace the second ? by &
return HttpResponseRedirect('add_scenes?submitted=True&linkToPrevScene=%s'%ScenePrevious)
Sorry I couldn't comment but you need to pass the parameter linkToPrevScene through the view for you to receive it in the template.
**Note:**In Django You can not pass parameters with redirect. Your only bet is to pass them as a part of URL.
#...Rest of your view...
context['linkToPrevScene'] = Water2
redirect(reverse('add_scenes?submitted=True?linkToPrevScene=%s'%ScenePrevious, kwargs={ 'linkToPrevScene': Water2 }))
Use the links below for reference
Django documentaion:
Reverse
Redirect

How do I call my dict parameters from the view.py render in my template?

I have been working on this for two day, and have read almost every example on stackoverflow and consulted the django documentation. I am trying to pass my dict from the views.py to my template, but I keep getting the stupid "Could not parse the remainder" error. I'm not doing anything fancy. Just Href buttons passing in a parameter to represent what that button is. Then a template page opens using that parameter as a string to make the new page and url unique.
pass in with:
Call
urls.py
urlpatterns = [
url(r'^call=(\d+)/$', views.call, name='call')
]
views.py
def call(request, callID):
call_id = { 'id':callID }
return render(request, 'site/call.html', call_id)
Call template
{% extends 'site/layout.html' %}
{% block content %}
{% with call_id.get('id') as view_id %}
<h3 class="center-align blue lighten-3">Site # Room {{ view_id }}</h3>
Cancel
{% endwith %}
{% endblock %}
I have tried request.GET.get('id') and a bizillion other things. Can someone show me how I can actually parse those dict values I passed in?
You're not actually passing a dictionary at all. You're passing a single value, id, so you should just use that. And there is no need for any with block.
Site # Room {{ id }}

Django template - dynamic variable name

Good Afternoon,
How can I use a variable variable name in Django templates?
I have a custom auth system using context, has_perm checks to see if the user has access to the specified section.
deptauth is a variable with a restriction group name i.e SectionAdmin. I think has.perm is actually checking for 'deptauth' instead of the variable value SectionAdmin as I would like.
{%if has_perm.deptauth %}
How can I do that? has_perm.{{depauth}} or something along those lines?
EDIT - Updated code
{% with arg_value="authval" %}
{% lookup has_perm "admintest" %}
{% endwith %}
{%if has_perm.authval %}
window.location = './portal/tickets/admin/add/{{dept}}/'+val;
{% else %}
window.location = './portal/tickets/add/{{dept}}/'+val;
{%endif%}
has_perm isn't an object.. it's in my context processor (permchecker):
class permchecker(object):
def __init__(self, request):
self.request = request
pass
def __getitem__(self, perm_name):
return check_perm(self.request, perm_name)
You're best off writing your own custom template tag for that. It's not difficult to do, and normal for this kind of situation.
I have not tested this, but something along these lines should work. Remember to handle errors properly!
def lookup(object, property):
return getattr(object, property)()
register.simple_tag(lookup)
If you're trying to get a property rather than execute a method, remove those ().
and use it:
{% lookup has_perm "depauth" %}
Note that has_perm is a variable, and "depauth" is a string value. this will pass the string for lookup, i.e. get has_perm.depauth.
You can call it with a variable:
{% with arg_value="depauth_other_value" %}
{% lookup has_perm arg_value %}
{% endwith %}
which means that the value of the variable will be used to look it up, i.e. has_perm.depauth_other_value'.
You can try like this,
{{ dict|key:key_name }}
Filter:
def key(d, key_name):
return d[key_name]
key = register.filter('key', key)
More information, django ticket

Django alter current URL name and arguments

In my Django URLs, I have many URL patterns that end with :
(redirect/(?P<redirect_to>\w+))
Which means that these URLs can be (or not) ending by /redirect/TARGET/. These URL patterns have other named arguments (mostly one : pk)
Now, I'd like, in the templates used by these URL patterns, to be able to alter the current page path, by just adding the redirect_to argument, and keeping the other arguments and URL reverse name untouched.
I was able to get the URL reverse name in the template, by adding resolve(path).url_name to the current context, and then to use that with the {% url %} template tag.
I'd like to know if there is any easy way to dynamically add the arguments (from resolve(path).kwargs) to the URL reverse tag ?
I think you should create a custom tag for this (replacing your {% url %} tag with {% url_redirect "your_new_destination" %}).
in your_app/templatetags/my_custom_tags.py:
from django.core.urlresolvers import reverse, resolve
#register.simple_tag(takes_context=True)
def url_redirect(context, new_destination):
match = resolve(context.request.path)
match.kwargs['redirect_to'] = new_destination
return reverse(match.url_name, args=match.args, kwargs=match.kwargs)
in your template:
{% load my_custom_tags %}
{% url_redirect "your_new_destination" %}
Please note that you need to add 'django.core.context_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS in order for this snippet to work.

Django: Calling views.py with argument

Hi Stackoverflow people,
I am using the Userena package for my user registration site. The package allows to change the template or the form class during with the call of the views.py function "def profile_edit" (if I understood it correctly).
The full header of the view function is:
def profile_edit(request, username, edit_profile_form=EditUserProfileForm,
template_name='userena/profile_form.html', success_url=None,
extra_context=None):
The demo project calls the view function in the template through the urls.py with the statement
{% url userena_profile_edit user.username %}
When I try to change the form parameter for example with
{% url userena_profile_edit user.username edit_profile_form=EditUserProfileForm %}
I get the follow error, which does not make sense to me:
Caught ValueError while rendering: Don't mix *args and **kwargs in call to reverse()!
I have also tried to the specify the kwargs dict, but it did not work either.
{% url userena_profile_edit user.username kwargs={'edit_profile_form':EditUserProfileForm} %}
How can I correctly call the function? I am confused why the last statement would not work.
Thank you for your help!
That's because your mixing args and kwargs. You can't do that in a reverse call. user.username is an arg, try using it as a kwarg:
{% url userena_profile_edit username=user.username edit_profile_form=EditUserProfileForm %}
how about making the username a kwarg?
{% url userena_profile_edit username=user.username edit_profile_form=EditUserProfileForm %}