Errors when passing a list through URL in Django - python

I try to pass a list through an URL in Django.
I found this: Passing a list through url in django
But I still get Errors. I feel like Iam running in a circle.
My urls:
path('query/', include(('query.urls', 'query-space'), namespace='query-space')),
re_path(r'^2/(?P<amb_list>\w+)/$',views.ambitionGenPage, name='userambitiongen'),
My views:
def ambitionPage(request):
if request.method == 'POST':
form = AmbitionForm(request.POST)
if form.is_valid():
ambs_list = form.cleaned_data['ambition_field']
redirect = HttpResponseRedirect(reverse('query-space:userambitiongen'))
redirect['Location'] += '&'.join(['ambs={}'.format(x) for x in ambs_list])
return redirect
form = AmbitionForm()
return render(request, 'query/ambition.html',{'form':form,})
def ambitionGenPage(request):
ambitions = request.GET.getlist('amb_list')
if ambitions:
ambitions = [int(x) for x in ambitions]
print(ambitions) #I first want to check what data I get
return render(request, 'query/ambitionGen.html',{})
I adapted the code of the link.
In the line:
redirect = HttpResponseRedirect(reverse('query-space:userambitiongen', args=(amb_list)))
he doesnt know the argument:
NameError: name 'amb_list' is not defined
In the example there is no argument. When I try this I get the error:
Reverse for 'userambitiongen' with no arguments not found. 1 pattern(s) tried: ['query/2/(?P<amb_list>\\w+)/$']
I also found nothing in the internet to this expression: redirect['Location']
Could someone explain to me what ['Location'] stands for?
What would be the right solution? I tried to find it by myself in many hours.
Thank you very much for your time!

return redirect['Location']
Redirects you to example: yourwebpage.com/Location
You can save the list into a sql database temporarily and later delete it.

Related

NoReverseMatch in Django 1.11

I know there are lot of questions already ask about this error but for some reason none of them work for me.
What i am trying to do?
I am trying to pass a variable from view ActivateAccount to another view result upon email confirmation.
What is the problem?
I am doing everything right according to docs and previously posted question about the same error but i still get this error:
Reverse for 'result' with keyword arguments '{'test': 'Email confirmed successfully!'}' not found. 1 pattern(s) tried: ['(?P<test>[\\w-]+)/$']
caller view.py:
def ActivateAccount(request, uidb64, token):
test = ''
if uidb64 is not None and token is not None:
...
test = "Email confirmed successfully!"
return HttpResponseRedirect(reverse('result', kwargs={'test': test}))
urls.py:
url(r'^(?P<test>[\w-]+)/$', views.result, name='result')
receiver view.py:
def result(request, test=None, *args, **kargs):
data = {'msg': test}
return JsonResponse(data) // this return the result to ajax 'GET'
And i would also like to know why is there double backslash \\ in the regex ([\\w-]) instead of single in the error. As in my url i have a single \ ([\w-]).
thanks for your time.
url(r'^(?P<test>[a-zA-Z!\s]+)/$', views.result, name='result')
use this urlpattern

Django pass empty parameter

I'm trying to pass an empty parameter to render a template but I can not achieve this I do not know if the problem is in urls.py or views, I really appreciate a hand.
Urls
url(r'^hola/(\b[a-z\.-]+)$', views.hola, name='hola'),
Views
def hola(request, varr = ''):
#val = val
pregunta = Datos_usuario_DB.objects.all().order_by('-id').filter(activo="1")[:15]
plantilla = {'': 'index.html', 'nosotros': 'nosotros.html'}
return render(request, plantilla['%s' % varr], {'pregunta': pregunta})
When I access to hola/ it says that the website does not exist.
If you want /hola/ to work, it's easy to add another URL pattern:
url(r'^hola/$', views.hola, name='hola'),
url(r'^hola/([a-z\.-]+)$', views.hola, name='hola'),
It's not clear to me why you have \b in the regex, so I removed it.
your urls is not contains hola/ entry, so It returns error.
If you want to call hola/, you need to add url in urls.py

How do you make a url that passes a parameter work in Django?

I'm working on registration logic and I can't seem to make the parameter pass in to work properly. The error I get is a 404 page not found. Previously, I also got a “The view didn't return an HttpResponse object" error. Any help is appreciated.
Here is my url from urls.py:
url(r'^accounts/confirm/(?P<activation_key>\d+)/$', 'mysite.views.confirm', name='confirm'),
This is my views.py:
def confirm(request, activation_key):
if request.user.is_authenticated():
HttpResponseRedirect('/home')
user = Hash.objects.filter(hash_key = activation_key)
if user:
user = Hash.objects.get(hash_key = activation_key)
user_obj = User.objects.get(username= user.username)
user_obj.is_active = True
user_obj.save()
HttpResponseRedirect('/home')
I send the url with a string that looks like:
"Click the link to activate your account http://www.example.com/accounts/confirm/%s" % (obj.username, activation_key)"
So the link looks like this:
http://www.example.com/accounts/confirm/4beo8d98fef1cd336a0f239jf4dc7fbe7bad8849a127d847f
You have two issues here:
Remove the trailing / from your pattern, or make it /? so it will be optional.
/d+ will only match digits, and your link also contains other characters. Try [a-z0-9]+ instead.
Complete pattern:
^accounts/confirm/(?P<activation_key>[a-z0-9]+)$
Remove / from end of your url:
url(r'^accounts/confirm/(?P<activation_key>\d+)$', 'mysite.views.confirm', name='confirm'),
or add / to end of your link:
http://www.example.com/accounts/confirm/4beo8d98fef1cd336a0f239jf4dc7fbe7bad8849a127d847f/

Django reverse URL issue

I'm having issues getting the following code (below) to work (there are no errors) . In my template I'm outputting item.get_settings_url but I get nothing. What I'm I doing wrong here?
In my models I have the following model method:
def get_settings_url(self):
return reverse('sms.views.keyword_settings', args=[str(self.keyword)])
urls:
url(r'^keyword/^(?P<keyword>[\.\w-]+)/settings/$', views.keyword_settings, name='keyword_settings')
view:
def keyword_settings(request, keyword):
return render_to_response('keyword_settings.html', context_instance=RequestContext(request))
Your URL contains a named parameter. Hence, you need to pass that name when calling reverse. Also, you should use the name of the URL to make the reverse lookup short and easier to maintain:
return reverse('keyword_settings', kwargs={'keyword': str(self.keyword)})

implementation difficulties in some part of views.py file in django cms

My views.py code:
from django.template import Context, loader, RequestContext
from django.http import HttpResponse
from skey import find_root_tags, count, sorting_list
from search.models import Keywords
def front_page(request):
if request.method == 'get' :
str1 = request.getvalue['word']
fo = open("xml.txt","r")
for i in range(count.__len__()):
file = fo.readline()
file = file.rstrip('\n')
find_root_tags(file,str1,i)
list.append((file,count[i]))
sorting_list(list)
for name, count in list:
s = Keywords(file_name=name,frequency_count=count)
s.save()
fo.close()
return HttpResponseRedirect('/results/')
else :
str1 = ''
list = []
template = loader.get_template('search/front_page.html')
c = RequestContext(request)
response = template.render(c)
return HttpResponse(response)
def results(request):
list1 = Keywords.objects.all()
t = loader.get_template('search/results.html')
c = Context({'list1':list1,
})
return HttpResponse(t.render(c))
#this for everyone.
the flow is this:
1) I run my app on the server .
2)It shows me the search page due to the else part of the view "def front_page(request)", now I want to execute the if part of the view "def front_page(request)" because I want to execute my python code written there and the redirected to the view "def results(request)", how can I do that ?
3) what should I mention in "action" of the front_page.html and in urls.py so that I can get back to the same view again. because I could'nt get back to the same view that I want it is repetitively showing me the same search page.Please help.
To enlarge upon the answer posted by #Barnaby....by using action='#' your form will be posted to the same url as the url used in the get request for the form.
Then in your view code, you have logic that says - if the request for this url is a GET request then do the work to configure the form, otherwise, you assume it is a POST and then you can handle the response.
Additionally I would advise that the your view explicitly checks that the request is a POST and if not make the assumption that it is a GET, rather than the other way around (as you have it), this is safer, as GET and POST are not the only request types, and you definitely need to know that you are dealing with a POST request if you want to deal with variables submitted in the POST request.
Hope that helps
Short answer: action="#". This is a HTML trick to post back to the current URL.
The general answer to how to reference a view in a template is to use the url tag. You may also want to consider using Django's forms functionality.

Categories