I write a message board,When user leave message and success back to the page
I want to alert('sucess leaving message,Thank you very much.')
I found a method is to use return redirect(reverse(...))
But there is an error when I try :
Reverse for '/maininfo/#5thPage' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Please help me ,Thank you .
views.py
def maininfo(request):
return render(request, 'zh_tw/maininfo.html',)
def create_post(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.save()
# return HttpResponseRedirect('/maininfo/#5thPage')
return redirect(reverse("/maininfo/#5thPage"), {"alert":'sucess leaving message,Thank you very much.'})
return render(request, "zh_tw/maininfo.html",{'form': form,'anchor':'#5thPage'})
urls.py
urlpatterns = patterns('',url(r'^maininfo/$', views.maininfo, name='maininfo'),)
template: zh_tw/contact.html
(this is an anchor page included by zh_tw/maininfo.html)
<script type="text/javascript">
$( document ).ready(function() {
{% if alert %}
alert('{{alert}}');
{% endif %}
});
</script>
The argument for reverse is the name or the view module in the urlpattern. In your case, it should be
views.maininfo
or
'maininfo'
Moreover, $ indicates the end of a string in Python regular expression. Thus you may not be able to resolve the '/maininfo/#5thPage' using the pattern ^maininfo/$. Find more info here :https://docs.djangoproject.com/en/dev/topics/http/urls/ .
Related
Trying to create an update function for a Project Model in Django but i've run into a problem. Here's what i have so far
update view function
#login_required
def updateProject(request, pk):
project = Project.objects.get(id=pk)
form = ProjectForm(instance=project)
if request.method == 'POST':
project.name = request.POST.get('name')
project.description = request.POST.get('description')
project.save()
return redirect('project', pk=project.id)
context = {'form': form, 'project': project}
return render(request, 'projects/project_form.html', context)
This is how I'm calling it in the template
<li>Edit</li>
and this is what the urlpattern is
path('update-project/<int:pk>/', views.updateProject, name='update-project'),
What am I missing?
To redirect to another URL I usually use:
return HttpResponseRedirect(reverse('update-project', args=(project.id,)))
instead of your
return redirect('project', pk=project.id)
which probably causes your error after POST
I'm currently just learning Django and I'm doing electronic grade book. I have tried everything, have read all the documentation, but nothing helps. It seems I miss a simple logic somewhere. I need to make two pages:
The first one "teacher_interface" is a simple inteface for the teacher with just one drop-down list, teacher chooses the necessary class (i.e 1C, 2B, 4C) and the button "Students", which should somehow take the chosen class from drop-down list input and redirect to the second page "class_students".
The second "class_students" is alike the "teacher_interface", but with the table of students of the chosen class.
I have the One-to-many relation between classes Student and Class:
Firstly, I tried redirecting from "teacher_interface" to "class_students", using in template:
{% url "name" %}
Parts of code: 1) models.py https://dpaste.org/eqxm 2) urls.py https://dpaste.org/eUEO 3) views.py https://dpaste.org/ap8D#L 4) template teacher_interface.html https://dpaste.org/v4m9 5) template class_students.html https://dpaste.org/0gXK
But it shows me: Reverse for 'class_students' with no arguments not found. 1 pattern(s) tried: ['school/teacher/(?P<class_id>[0-9]+)/class/$']
I tried everything, but nothing helped, this and the similar: Django - getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %} I understood maybe this two options of redirect will not work in my case:
{% url 'class_students' class.id %}
{% url 'class_students' class_id %}
I also don't know if it's possible to do on the same page.
So I decided to redirect using redirect from django.shortcuts. I changed my teacher_interface view, so that it took the id of the chosen by the teacher class if request method is POST and redirected. I also made this change in my template "teacher_interface.html":
from
action="{% url 'class_students' %}"
to
action=""
Changed view:
def teacher_interface(request):
class_queryset = Class.objects.order_by("class_number", "group")
class_id = None
if request.method == "POST":
class_id = Class.objects.get("id")
return redirect("class_students", class_id)
context = {
"class_queryset": class_queryset,
"class_id": class_id,
}
return render(request, "teacher_interface.html", context)
But when I choose the class and click the "Students" button, it shows me: Cannot resolve keyword 'i' into field. Choices are: class_number, curriculum, discipline, group, id, student, task, type_of_class, type_of_class_id. Id is certainly is a key, but it tries to resolve only "i".
I tried/read everything here, but nothing works.
I even wrote the default like this:
class_id = Class.objects.get("id", "default")
I am sure I just don't understand properly how to get teacher's choice, pass it to another or the same function and redirect, saving this information. I will be really grateful for you help, even if you just advise what I can read to figure it out.
Ok, you are missing some basic conpects.
on your views.py
def teacher_interface(request):
class_queryset = Class.objects.order_by("class_number", "group")
context = {
"class_queryset": class_queryset,
}
return render(request, "teacher_interface.html", context)
this is correct, you will pass you query to your template
on your template change some things to look like this:
<form method="POST" >{% csrf_token %}
<select name="input1">
{% for class in class_queryset %}
<option value="{{ class.id }}">{{ class }}</option>
{% endfor %}
</select>
<input type="submit" value="Students"/>
</form>
then you need to change your teacher_interface view:
You need to import redirect on your views.py
def teacher_interface(request):
class_queryset = Class.objects.order_by("class_number", "group")
context = {
"class_queryset": class_queryset,
}
if request.method == 'POST':
class_id = request.POST.get('input1') # I'm not sure if this will get the {{class.id}} value, if don't, print(request.POST.get) and check how to get the value
return redirect('class_students', class_id=class_id) # will make a get request on the class_students view
return render(request, "teacher_interface.html", context)
def class_students(request, class_id):
# the parameter need to be 'class_id' because this is what you put on your urls '<int:class_id>', if possible, remove that /class.
# ADD CLASS ID AS PARAMETER, THAT WILL ENABLE YOU TO ACESS AN SPECIFIC CLASS
# Import get_object_or_404 (google it and you will find easily)
class = get_object_or_404(Class, pk=class_id) # this avoid internal server error.
# pass your class on the context
return render(request, "class_students.html")
Django URL pattern not recognized due to tuple entry
I want to put a hyperlink in HTML code to redirect to a page with sending data with it. hyperlink path is dynamic so I used {% url "check" book.id %} in HTML code. book.id gives correct data but it appears in tuple format ('12',)
when I call particular page by writing static URL like http://127.0.0.1:8000/check/12/ it works fine "check" as view area and 12 as an argument passed
how to use a dynamic path
views.py
def add(request):
book = Readdata.objects.all()
return render(request, 'result.html', {'books': book})
def check(request,id):
return render(request,'result.html',{'result': id})
urls.py
urlpatterns = [
url('add', views.add, name='add'),
url(r'^check/(\d+)/$', views.check, name="delete_book"),
url('', views.index, name="index")
]
html
click not working
click working
error-
Reverse for 'check' with arguments '(21,)' not found. 1 pattern(s)
tried: ['check']
This has nothing to do with tuples.
As the error says, you don't have a "check" URL that takes an argument "21". The only URL that takes an argument is "delete_book". "check" takes no arguments.
So say I have a view called addPost(like a wall post). It's a model form page for a post object. There are two cases, either the request.method is post, or it isn't. In the case that it's a POST method, I want to return to the profile page after the post is submitted.
I've had this problem a few times, and it usually comes in the form of NoReverseMatch Errors.
How do you "return render/Httpresponse/etc" to another view? in Django? I feel like any solutions I've had before have been really hackish and I want to proper way to implement this sort of feature.
I do want to note that I get this error on myapp/profile.html
Here is the trackback I have:
NoReverseMatch at /myapp/profile/1/
Reverse for 'addpost' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Request Method: GET
Request URL: http://127.0.0.1:8000/myapp/profile/1/
Django Version: 1.8.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'addpost' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Exception Location: /Library/Python/2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 496
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.8
Python Path:
['/Users/me/project',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-18.0.1-py2.7.egg',
'/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages',
'/Library/Python/2.7/site-packages']
Server time: Tue, 14 Jul 2015 08:12:13 +0000
It occurs at this line of code in the html, the button that links to the add_post view.
profile.html
{% if user == currUser %}
<a href="
{% url 'addpost' %}
" class = "btn btn-info"> <span class="glyphicon glyphicon-plus"></span></a>
{% endif %}
and it highlights this bit of code in Debug:
~/myapp/views.py in profile
return render_to_response('myapp/profile.html', {'currUser': currUser}, context) ...
▼ Local vars
Here are the two views, profile and add_post.
#login_required
def profile(request, id):
context = RequestContext(request)
currUser = User.objects.get(pk = id)
profile = UserProfile.objects.filter(user = currUser)
return render_to_response('myapp/profile.html', {'currUser': currUser}, context)
#login_required
#login_required
def add_post(request):
context = RequestContext(request)
if request.method == 'POST':
# #create a form instance and populate it with data from the request
form = PostForm(request.POST)
if form.is_valid():
#process data in form.clean_data
post = Post(user = request.user, title =form.cleaned_data['title'], body=form.cleaned_data['body'])
post.save()
return redirect(reverse('myapp/profile', args=[request.user.pk]))
else:
form=PostForm()
return render_to_response('myapp/addpost.html', {'form': form}, context )
urls.py
urlpatterns = patterns(
'',
...
url(r'^profile/(?P<id>\d+)/$', views.profile, name='profile'),
url(r'^addpost/$', views.add_post, name='add_post'),
)
You've misdiagnosed the problem. It is nothing to do with redirecting; it occurring in the template itself, because you have used {% url 'addpost' %} instead of {% url 'add_post' %}.
Just redirect, you don't need to do a render_to_response.
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
#login_required
def add_post(request):
....
if form.is_valid():
....
return redirect(reverse('profile', args=[request.user.pk]))
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