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"),
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.
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
I am trying to redirect users to a create-profile form after signup.Since I don't know how to use dynamic url for LOGIN_REDIRECT_URL.I tried this little trick of linking it to a static view then finally to a dynamic view using redirect.It gives the error Reverse for 'add_profile' with arguments '()' and keyword arguments '{'username': u'badguy'}' not found. 0 pattern(s) tried: [] (with 'badguy' truly the username of the just signed-up user').From the error,it is clearly passing the username to the view.My codes are:
settings.py
LOGIN_REDIRECT_URL = '/prof-change/gdyu734648dgey83y37gyyeyu8g/'
urls.py
url(r'^prof-change/gdyu734648dgey83y37gyyeyu8g/',views.login_redir,name='login_redir'),
url(r'^create-profile/(?P<username>\w+)/$',views.add_profile,name='create-profile'),
views.py
def login_redir(request):
user=get_object_or_404(User,username=request.user.username)
username=user.username
return redirect('add_profile',username=username)
def add_profile(request,username):
userman=User.objects.get(username=username)
........
........
When you reverse urls (including when you use a url name with the redirect shortcut), you should use the name of the url pattern, not the view. The url pattern has name='create-profile', so use that.
redirect('create-profile', username=username)
I am in the processing of developing a Django application. I had spent around 40-50 hours researching Django, and I am well on my way to making an application!
However, I am starting to come across "more serious" errors, as some might call them, as I am not able to figure out from my stack trace exactly what the real problem is.
Basically, I click a link on my page, and this error pops up:
Request Method: GET
Request URL: /accounts/profile/
Django Version: 1.5.1
Exception Type: ValueError
Exception Value:
*The view userprofile.views.user_profile didn't return an HttpResponse object.*
That leads me to believe the error is in my views file, except that I was following a tutorial line for line, and I am led to believe the error might be in how forms.py is being used to create the HttpResponse object.
The code in short, is,
form = UserProfileForm(request.POST, instance=request.user.profile)
...
args = {}
args.update(csrf(request)) // security token
args['form'] = form
return render_to_response('profile.html', args)
profile.html is also definitely fine, I tested that, and I am basically calling this from a loggedin.html page where I display a valid user login.
Thanks so much for your help SO, I don't usually ask questions, but I have been stuck on this problem alone for 5-6 development hours. Try not to mock me for not understanding this likely-simply but hidden-to-beginner error :)
Also, I would prefer in the response if you could indicate how you went about solving this error, especially indicating how my thinking is and where the root misunderstanding is.
And in your answers, only reference specific instances of the docs, because I've done plenty of searching, but perhaps it isn't narrowed down quite to what my issue is :D
Thanks again,
James
Comment One: Tutorial
Here is the tutorial I am referring to. I am getting stuck in identifying the bug, as I have all of the code and everything worked until I tried clicking the hyperlink. I am not experienced to where the error is coming from.
Second Comment: Relevant Code
userprofile/views.py
def user_profile(request):
if request.method=='POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request)) // security token
args['form'] = form
return render_to_response('profile.html', args)
myapp urls.py , userprofile urls.py
(r'^accounts/', include ('userprofile.urls')),
...
url(r'^profile/$', 'userprofile.views.user_profile'),
If that's really your view code, it's a simple indentation error. It should be:
def user_profile(request):
if request.method=='POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request)) // security token
args['form'] = form
return render_to_response('profile.html', args)
What's going on is that when request.METHOD is GET, there's no else clause on the initial if, so the view function ends without returning anything. Instead, you want to create the form, add it to the context, and render it - either because it's a GET request or because there were errors in the form, and you want to rerender the context to show those errors and allow the user to correct them.
I seem to be getting a Caught NoReverseMatch error. I am not so sure what is causing the problem. Have a look at the full error.
Caught NoReverseMatch while rendering: Reverse for 'mmc.views.edit_note' with arguments '(1L, '')' and keyword arguments '{}' not found.
On my get_client page. I have a link to the edit note page. I am assuming the problem might be here in my template. I think the note.pk is the problem.
Edit Note
Here is also some more information which could help.
urls.py
(r'^clients/(?P<client_id>\d+)/$', views.get_client),
(r'^clients/notes/(?P<client_id>\d+)(?P<note_id>\d+)$', views.edit_notes),
views.py
#login_required
def edit_notes(request, client_id = 0, note_id = 0):
client = None
note = None
try:
client = models.Client.objects.get(pk = client_id)
note = models.Note.objects.get(pk = note_id)
except:
return HttpResponseNotFound()
if request.method == 'POST':
form = forms.NoteForm(request.POST, instance=note)
if form.is_valid():
note = form.save(commit=False)
note.user = request.user
note.client = client
note.save(True)
request.user.message_set.create(message = "Note is successfully added.")
return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")
else:
form = forms.NoteForm(instance=note)
return render_to_response('note_form.html', {'form':form, 'client':client, 'note':note}, context_instance = RequestContext(request))
*EDIT: * Seem to have corrected most of it Here are some changes I have made.
Template
{% for note in notes %}
Edit Note
{% endfor%}
urls.py
(r'^clients/notes/(?P<client_id>\d+)/(?P<note_id>\d+)/$', views.edit_note)
Now the only problem is it displays all of the links to each edit form notes for an individual client. I only want the link for the latest note and only the latest note. Is there a possible way?
The client.pk and note.pk are empty values, so they don't match the regex.
(r'^clients/(?P<client_id>\d+)/$', views.get_client) should be something like url(r'^clients/(?P<client_id>\d+)/$', views.get_client, name='MY_URL_NAME') then called with {% url MY_URL_NAME client.pk %}
and import url from django.conf.urls.defaults