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
Related
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.
so I been working on this for a couple of days now and I still dont seem to understand the problem. I am trying to get the username in the url so that you can just look up any user if you type http://127.0.0.1:8000/accounts/profile/username and that users profile shows up. I have looked at other questions but I keep getting this error when I try. If anyone could help me I would be greatly appreciated.
NoReverseMatch at /accounts/profile/admin
Reverse for 'viewprofile' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts/profile/(?P[\w.#+-]+)']
views.py
def view_profile(request, username):
username = User.objects.get(username=username)
posts = Post.objects.filter(author = request.user).order_by('-pub_date')
args = {
'user': request.user,
'posts': posts,
}
return render(request, 'accounts/profile.html', args)
in my nav bar: this could be wrong but im sure its right
<li>Profile</li>
urls.py
url(r'^profile/(?P<username>[\w.#+-]+)', views.view_profile, name="viewprofile"),
You give user key in your context, you use username in your template. Maybe that's the problem.
The URL which you're trying to match to if failing, please try this:
url(r'profile/(?P<username>[a-zA-Z0-9]+)$', views.view_profile, name="viewprofile"),
Trying to access part of code by get request and receiving this error
NoReverseMatch: Reverse for 'homepage' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] looked around for help and i think its that am missing some arguments.
here is request am using in my test
req = self.client.get('/password/reset/')
and the code it leads to is as:
class PasswordResetEmailView(FormView):
template_name = 'temp/password_reset.html'
form_class = PasswordResetForm
success_url = 'password_reset_ok'
def get(self, request, *args, **kwargs):
form = self.get_form(self.form_class)
return self.render_to_response(self.get_context_data(form=form))
any guidance ?
You ask specifically about "determining which arguments are missing", but should be irrelevant to your error.
Your error message states that it can't find any URL patterns matching the name "homepage", before attempting any argument matching. Therefore no URLs exist named "homepage" in your setup. If it was an argument mismatch, you'd see a list of named URLs in the error such as "tried X urls."
Either define a URL named home in your URLConf url(r'^home/$', 'home_view', name="homepage") or find the location that is calling reverse('homepage') and remove it. You will find this information in your traceback.
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/
How do I use Django's Reverse with an optional parameter for info? I keep on getting
views.py:
def cartForm(request, prod):
if request.method=="POST":
quantity = request.POST.get('quantity', False)
if quantity:
add_to_cart(request, prod, quantity)
return HttpResponseRedirect(reverse("cart"))
#if no quantity indicated, display error message
return HttpResponseRedirect(reverse('products.views.info', kwargs={'prod': prod, 'error':True}))
def info(request, prod, error=False):
prod = Product.objects.get(id=prod)
return render(request, "products/info.html", dict(product = prod, error=error))
urls.py:
url(r'^(?P<prod>\d+)/', "products.views.info", name='info'),
I keep on getting the following error:
Reverse for 'products.views.info' with arguments '()' and keyword arguments '{'prod': u'2', 'error': True}' not found. 1 pattern(s) tried: ['products/(?P<prod>\\d+)/']
You can pass optional GET parameters as:
reverse('products.views.info', kwargs={'prod': prod})+'?error=true&some_other_var=abc'
reverse returns the resolved URL as string, so you can concatenate as many GET parameters as you want.
Not a direct answer but : why don't you just use the Messages framework (https://docs.djangoproject.com/en/1.6/ref/contrib/messages/).
Try with optional group in url:
# change (?P<error>\d+) to (?P<error>[a-zA-Z]+) to catch strings in error value
url(r'^(?P<prod>\d+)(?:/(?P<error>\d+))?/', "products.views.info", name='info'),
source: Making a Regex Django URL Token Optional
Adding an argument to the view function doesn't not make it into a URL pattern, in your case you have added the argument directy to the view method, but not mapped it to the URL.
Therefore, when you try to reverse the URL, a pattern that has error is not found, which is why you are getting the error.
You have two options:
Make the pattern optional which I do not recommend.
Map the same view to multiple URLs, with the optional one first as the patterns are matched in the order found:
url(r'^(?P<prod>\d+)/(?P<error>\d+)/', "products.views.info", name='info-error'),
url(r'^(?P<prod>\d+)/', "products.views.info", name='info'),
Now, in your view:
from django.shortcuts import redirect
def cartForm(request, prod):
if request.method=="POST":
quantity = request.POST.get('quantity', False)
if quantity:
add_to_cart(request, prod, quantity)
return HttpResponseRedirect(reverse("cart"))
#if no quantity indicated, display error message
return redirect('info-error', prod=foo, error=True)
Here I am using the redirect shortcut